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",Name.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)
119 while (Route->GetParent() != TreeRoot)
120 Route = Route->GetParent();
122 log(DEBUG," ROUTE FOR %s is %s",Name.c_str(),Route->GetName().c_str());
125 TreeServer* GetRoute()
130 std::string GetName()
132 return this->ServerName;
135 std::string GetDesc()
137 return this->ServerDesc;
140 std::string GetVersion()
142 return this->VersionString;
145 void SetNextPingTime(time_t t)
148 LastPingWasGood = false;
151 time_t NextPingTime()
153 return this->NextPing;
156 bool AnsweredLastPing()
158 return LastPingWasGood;
163 LastPingWasGood = true;
168 return this->UserCount;
173 return this->OperCount;
176 TreeSocket* GetSocket()
181 TreeServer* GetParent()
186 void SetVersion(std::string Version)
188 VersionString = Version;
191 unsigned int ChildCount()
193 return Children.size();
196 TreeServer* GetChild(unsigned int n)
198 if (n < Children.size())
208 void AddChild(TreeServer* Child)
210 Children.push_back(Child);
213 bool DelChild(TreeServer* Child)
215 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
226 // removes child nodes of this node, and of that node, etc etc
229 bool stillchildren = true;
230 while (stillchildren)
232 stillchildren = false;
233 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
235 TreeServer* s = (TreeServer*)*a;
239 stillchildren = true;
253 std::string SendPass;
254 std::string RecvPass;
255 unsigned long AutoConnect;
256 time_t NextConnectTime;
259 /* $ModDesc: Povides a spanning tree server link protocol */
263 std::vector<Link> LinkBlocks;
265 TreeServer* RouteEnumerate(TreeServer* Current, std::string ServerName)
267 if (Current->GetName() == ServerName)
268 return Current->GetRoute();
269 for (unsigned int q = 0; q < Current->ChildCount(); q++)
271 TreeServer* found = RouteEnumerate(Current->GetChild(q),ServerName);
273 return found->GetRoute();
278 // Returns the locally connected server we must route a
279 // message through to reach server 'ServerName'. This
280 // only applies to one-to-one and not one-to-many routing.
281 TreeServer* BestRouteTo(std::string ServerName)
283 if (ServerName.c_str() == TreeRoot->GetName())
287 // first, find the server by recursively walking the tree
288 TreeServer* Found = RouteEnumerate(TreeRoot,ServerName);
292 bool LookForServer(TreeServer* Current, std::string ServerName)
294 if (ServerName == Current->GetName())
296 for (unsigned int q = 0; q < Current->ChildCount(); q++)
298 if (LookForServer(Current->GetChild(q),ServerName))
306 void RFindServer(TreeServer* Current, std::string ServerName)
308 if ((ServerName == Current->GetName()) && (!Found))
315 for (unsigned int q = 0; q < Current->ChildCount(); q++)
318 RFindServer(Current->GetChild(q),ServerName);
324 void RFindServerMask(TreeServer* Current, std::string ServerName)
326 if (Srv->MatchText(Current->GetName(),ServerName) && (!Found))
333 for (unsigned int q = 0; q < Current->ChildCount(); q++)
336 RFindServerMask(Current->GetChild(q),ServerName);
341 TreeServer* FindServer(std::string ServerName)
344 RFindServer(TreeRoot,ServerName);
348 TreeServer* FindServerMask(std::string ServerName)
351 RFindServerMask(TreeRoot,ServerName);
355 bool IsServer(std::string ServerName)
357 return LookForServer(TreeRoot,ServerName);
360 class TreeSocket : public InspSocket
363 std::string in_buffer;
364 ServerState LinkState;
365 std::string InboundServerName;
366 std::string InboundDescription;
368 int num_lost_servers;
370 bool LastPingWasGood;
374 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
375 : InspSocket(host, port, listening, maxtime)
378 this->LinkState = LISTENER;
381 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
382 : InspSocket(host, port, listening, maxtime)
385 this->LinkState = CONNECTING;
388 TreeSocket(int newfd, char* ip)
389 : InspSocket(newfd, ip)
391 this->LinkState = WAIT_AUTH_1;
394 virtual bool OnConnected()
396 if (this->LinkState == CONNECTING)
398 Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
399 // we should send our details here.
400 // if the other side is satisfied, they send theirs.
401 // we do not need to change state here.
402 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
404 if (x->Name == this->myhost)
406 // found who we're supposed to be connecting to, send the neccessary gubbins.
407 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
415 virtual void OnError(InspSocketError e)
419 virtual int OnDisconnect()
424 // recursively send the server tree with distances as hops
425 void SendServers(TreeServer* Current, TreeServer* s, int hops)
428 for (unsigned int q = 0; q < Current->ChildCount(); q++)
430 TreeServer* recursive_server = Current->GetChild(q);
431 if (recursive_server != s)
433 // :source.server SERVER server.name hops :Description
434 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
435 this->WriteLine(command);
436 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
437 // down to next level
438 this->SendServers(recursive_server, s, hops+1);
443 void SquitServer(TreeServer* Current)
445 // recursively squit the servers attached to 'Current'
446 for (unsigned int q = 0; q < Current->ChildCount(); q++)
448 TreeServer* recursive_server = Current->GetChild(q);
449 this->SquitServer(recursive_server);
451 // Now we've whacked the kids, whack self
453 bool quittingpeople = true;
454 while (quittingpeople)
456 quittingpeople = false;
457 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
459 if (!strcasecmp(u->second->server,Current->GetName().c_str()))
461 Srv->QuitUser(u->second,Current->GetName()+" "+std::string(Srv->GetServerName()));
463 quittingpeople = true;
470 void Squit(TreeServer* Current,std::string reason)
474 std::deque<std::string> params;
475 params.push_back(Current->GetName());
476 params.push_back(":"+reason);
477 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
478 if (Current->GetParent() == TreeRoot)
480 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
484 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
486 num_lost_servers = 0;
488 SquitServer(Current);
490 Current->GetParent()->DelChild(Current);
492 WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
496 log(DEFAULT,"Squit from unknown server");
500 bool ForceMode(std::string source, std::deque<std::string> params)
502 userrec* who = new userrec;
503 who->fd = FD_MAGIC_NUMBER;
504 if (params.size() < 2)
507 for (unsigned int q = 0; q < params.size(); q++)
509 modelist[q] = (char*)params[q].c_str();
511 Srv->SendMode(modelist,params.size(),who);
512 DoOneToAllButSender(source,"FMODE",params,source);
517 bool ForceTopic(std::string source, std::deque<std::string> params)
519 // FTOPIC %s %lu %s :%s
520 if (params.size() != 4)
522 std::string channel = params[0];
523 time_t ts = atoi(params[1].c_str());
524 std::string setby = params[2];
525 std::string topic = params[3];
527 chanrec* c = Srv->FindChannel(channel);
530 if ((ts >= c->topicset) || (!*c->topic))
532 std::string oldtopic = c->topic;
533 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
534 strlcpy(c->setby,setby.c_str(),NICKMAX);
536 // if the topic text is the same as the current topic,
537 // dont bother to send the TOPIC command out, just silently
538 // update the set time and set nick.
539 if (oldtopic != topic)
540 WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
545 // all done, send it on its way
546 params[3] = ":" + params[3];
547 DoOneToAllButSender(source,"FTOPIC",params,source);
552 bool ForceJoin(std::string source, std::deque<std::string> params)
554 if (params.size() < 3)
558 char modestring[MAXBUF];
559 char* mode_users[127];
560 mode_users[0] = first;
561 mode_users[1] = modestring;
562 strcpy(mode_users[1],"+");
563 unsigned int modectr = 2;
566 std::string channel = params[0];
567 time_t TS = atoi(params[1].c_str());
570 chanrec* chan = Srv->FindChannel(channel);
575 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
577 // default is a high value, which if we dont have this
578 // channel will let the other side apply their modes.
579 time_t ourTS = time(NULL)+600;
580 chanrec* us = Srv->FindChannel(channel);
586 log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
588 // do this first, so our mode reversals are correctly received by other servers
589 // if there is a TS collision.
590 DoOneToAllButSender(source,"FJOIN",params,source);
592 for (unsigned int usernum = 2; usernum < params.size(); usernum++)
594 // process one channel at a time, applying modes.
595 char* usr = (char*)params[usernum].c_str();
596 char permissions = *usr;
601 mode_users[modectr++] = usr;
602 strlcat(modestring,"o",MAXBUF);
606 mode_users[modectr++] = usr;
607 strlcat(modestring,"h",MAXBUF);
611 mode_users[modectr++] = usr;
612 strlcat(modestring,"v",MAXBUF);
615 who = Srv->FindNick(usr);
618 Srv->JoinUserToChannel(who,channel,key);
619 if (modectr >= (MAXMODES-1))
621 // theres a mode for this user. push them onto the mode queue, and flush it
622 // if there are more than MAXMODES to go.
625 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
626 Srv->SendMode(mode_users,modectr,who);
630 log(DEBUG,"Their channel newer than ours, bouncing their modes");
632 std::deque<std::string> params;
633 // modes are now being UNSET...
634 *mode_users[1] = '-';
635 for (unsigned int x = 0; x < modectr; x++)
637 params.push_back(mode_users[x]);
639 // tell everyone to bounce the modes. bad modes, bad!
640 DoOneToMany(Srv->GetServerName(),"FMODE",params);
642 strcpy(mode_users[1],"+");
647 // there werent enough modes built up to flush it during FJOIN,
648 // or, there are a number left over. flush them out.
649 if ((modectr > 2) && (who))
653 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
654 Srv->SendMode(mode_users,modectr,who);
658 log(DEBUG,"Their channel newer than ours, bouncing their modes");
659 std::deque<std::string> params;
660 *mode_users[1] = '-';
661 for (unsigned int x = 0; x < modectr; x++)
663 params.push_back(mode_users[x]);
665 DoOneToMany(Srv->GetServerName(),"FMODE",params);
671 bool IntroduceClient(std::string source, std::deque<std::string> params)
673 if (params.size() < 8)
675 // NICK age nick host dhost ident +modes ip :gecos
677 std::string nick = params[1];
678 std::string host = params[2];
679 std::string dhost = params[3];
680 std::string ident = params[4];
681 time_t age = atoi(params[0].c_str());
682 std::string modes = params[5];
683 while (*(modes.c_str()) == '+')
685 char* m = (char*)modes.c_str();
689 std::string ip = params[6];
690 std::string gecos = params[7];
691 char* tempnick = (char*)nick.c_str();
692 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
694 user_hash::iterator iter;
695 iter = clientlist.find(tempnick);
696 if (iter != clientlist.end())
699 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);
700 this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
704 clientlist[tempnick] = new userrec();
705 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
706 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
707 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
708 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
709 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
710 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
711 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
712 clientlist[tempnick]->registered = 7;
713 clientlist[tempnick]->signon = age;
714 strlcpy(clientlist[tempnick]->modes, modes.c_str(),53);
715 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
716 for (int i = 0; i < MAXCHANS; i++)
718 clientlist[tempnick]->chans[i].channel = NULL;
719 clientlist[tempnick]->chans[i].uc_modes = 0;
721 params[7] = ":" + params[7];
722 DoOneToAllButSender(source,"NICK",params,source);
726 void SendFJoins(TreeServer* Current, chanrec* c)
729 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
730 std::vector<char*> *ulist = c->GetUsers();
731 for (unsigned int i = 0; i < ulist->size(); i++)
733 char* o = (*ulist)[i];
734 userrec* otheruser = (userrec*)o;
735 strlcat(list," ",MAXBUF);
736 strlcat(list,cmode(otheruser,c),MAXBUF);
737 strlcat(list,otheruser->nick,MAXBUF);
738 if (strlen(list)>(480-NICKMAX))
740 this->WriteLine(list);
741 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
744 if (list[strlen(list)-1] != ':')
746 this->WriteLine(list);
750 void SendChannelModes(TreeServer* Current)
753 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
755 SendFJoins(Current, c->second);
756 snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
757 this->WriteLine(data);
758 if (*c->second->topic)
760 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);
761 this->WriteLine(data);
763 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
765 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
766 this->WriteLine(data);
768 FOREACH_MOD OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this);
772 // send all users and their channels
773 void SendUsers(TreeServer* Current)
776 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
778 if (u->second->registered == 7)
780 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);
781 this->WriteLine(data);
782 if (strchr(u->second->modes,'o'))
784 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
786 //char* chl = chlist(u->second,u->second);
789 // this->WriteLine(":"+std::string(u->second->nick)+" FJOIN "+std::string(chl));
791 FOREACH_MOD OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this);
796 void DoBurst(TreeServer* s)
798 Srv->SendOpers("*** Bursting to "+s->GetName()+".");
799 this->WriteLine("BURST");
800 // send our version string
801 this->WriteLine(":"+Srv->GetServerName()+" VERSION :"+GetVersionString());
803 this->SendServers(TreeRoot,s,1);
804 // Send users and their channels
806 // Send everything else (channel modes etc)
807 this->SendChannelModes(s);
808 this->WriteLine("ENDBURST");
811 virtual bool OnDataReady()
813 char* data = this->Read();
816 this->in_buffer += data;
817 while (in_buffer.find("\n") != std::string::npos)
819 char* line = (char*)in_buffer.c_str();
820 std::string ret = "";
821 while ((*line != '\n') && (strlen(line)))
826 if ((*line == '\n') || (*line == '\r'))
829 if (!this->ProcessLine(ret))
835 return (data != NULL);
838 int WriteLine(std::string line)
840 return this->Write(line + "\r\n");
843 bool Error(std::deque<std::string> params)
845 if (params.size() < 1)
847 std::string Errmsg = params[0];
848 std::string SName = myhost;
849 if (InboundServerName != "")
851 SName = InboundServerName;
853 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
854 // we will return false to cause the socket to close.
858 bool OperType(std::string prefix, std::deque<std::string> params)
860 if (params.size() != 1)
862 std::string opertype = params[0];
863 userrec* u = Srv->FindNick(prefix);
866 strlcpy(u->oper,opertype.c_str(),NICKMAX);
867 if (!strchr(u->modes,'o'))
869 strcat(u->modes,"o");
871 DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
876 bool RemoteRehash(std::string prefix, std::deque<std::string> params)
878 if (params.size() < 1)
880 std::string servermask = params[0];
881 if (Srv->MatchText(Srv->GetServerName(),servermask))
883 Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
885 ReadConfiguration(false);
887 DoOneToAllButSender(prefix,"REHASH",params,prefix);
891 bool RemoteKill(std::string prefix, std::deque<std::string> params)
893 if (params.size() != 2)
895 std::string nick = params[0];
896 std::string reason = params[1];
897 userrec* u = Srv->FindNick(prefix);
898 userrec* who = Srv->FindNick(nick);
901 std::string sourceserv = prefix;
904 sourceserv = u->server;
906 params[1] = ":" + params[1];
907 DoOneToAllButSender(prefix,"KILL",params,sourceserv);
908 Srv->QuitUser(who,reason);
913 bool LocalPong(std::string prefix, std::deque<std::string> params)
915 if (params.size() < 1)
917 TreeServer* ServerSource = FindServer(prefix);
920 ServerSource->SetPingFlag();
925 bool ServerVersion(std::string prefix, std::deque<std::string> params)
927 if (params.size() < 1)
929 TreeServer* ServerSource = FindServer(prefix);
932 ServerSource->SetVersion(params[0]);
934 params[0] = ":" + params[0];
935 DoOneToAllButSender(prefix,"VERSION",params,prefix);
939 bool ChangeHost(std::string prefix, std::deque<std::string> params)
941 if (params.size() < 1)
943 userrec* u = Srv->FindNick(prefix);
946 Srv->ChangeHost(u,params[0]);
947 DoOneToAllButSender(prefix,"FHOST",params,u->server);
952 bool ChangeName(std::string prefix, std::deque<std::string> params)
954 if (params.size() < 1)
956 userrec* u = Srv->FindNick(prefix);
959 Srv->ChangeGECOS(u,params[0]);
960 params[0] = ":" + params[0];
961 DoOneToAllButSender(prefix,"FNAME",params,u->server);
966 bool LocalPing(std::string prefix, std::deque<std::string> params)
968 if (params.size() < 1)
970 std::string stufftobounce = params[0];
971 this->WriteLine(":"+Srv->GetServerName()+" PONG "+stufftobounce);
975 bool RemoteServer(std::string prefix, std::deque<std::string> params)
977 if (params.size() < 4)
979 std::string servername = params[0];
980 std::string password = params[1];
981 // hopcount is not used for a remote server, we calculate this ourselves
982 std::string description = params[3];
983 TreeServer* ParentOfThis = FindServer(prefix);
986 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
989 TreeServer* CheckDupe = FindServer(servername);
992 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
995 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
996 ParentOfThis->AddChild(Node);
997 params[3] = ":" + params[3];
998 DoOneToAllButSender(prefix,"SERVER",params,prefix);
999 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
1003 bool Outbound_Reply_Server(std::deque<std::string> params)
1005 if (params.size() < 4)
1007 std::string servername = params[0];
1008 std::string password = params[1];
1009 int hops = atoi(params[2].c_str());
1012 this->WriteLine("ERROR :Server too far away for authentication");
1015 std::string description = params[3];
1016 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1018 if ((x->Name == servername) && (x->RecvPass == password))
1020 TreeServer* CheckDupe = FindServer(servername);
1023 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1026 // Begin the sync here. this kickstarts the
1027 // other side, waiting in WAIT_AUTH_2 state,
1028 // into starting their burst, as it shows
1029 // that we're happy.
1030 this->LinkState = CONNECTED;
1031 // we should add the details of this server now
1032 // to the servers tree, as a child of the root
1034 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
1035 TreeRoot->AddChild(Node);
1036 params[3] = ":" + params[3];
1037 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
1038 this->DoBurst(Node);
1042 this->WriteLine("ERROR :Invalid credentials");
1046 bool Inbound_Server(std::deque<std::string> params)
1048 if (params.size() < 4)
1050 std::string servername = params[0];
1051 std::string password = params[1];
1052 int hops = atoi(params[2].c_str());
1055 this->WriteLine("ERROR :Server too far away for authentication");
1058 std::string description = params[3];
1059 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1061 if ((x->Name == servername) && (x->RecvPass == password))
1063 TreeServer* CheckDupe = FindServer(servername);
1066 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1069 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
1070 this->InboundServerName = servername;
1071 this->InboundDescription = description;
1072 // this is good. Send our details: Our server name and description and hopcount of 0,
1073 // along with the sendpass from this block.
1074 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
1075 // move to the next state, we are now waiting for THEM.
1076 this->LinkState = WAIT_AUTH_2;
1080 this->WriteLine("ERROR :Invalid credentials");
1084 std::deque<std::string> Split(std::string line, bool stripcolon)
1086 std::deque<std::string> n;
1087 if (!strchr(line.c_str(),' '))
1092 std::stringstream s(line);
1093 std::string param = "";
1112 if ((param == ":") && (item > 0))
1135 bool ProcessLine(std::string line)
1137 char* l = (char*)line.c_str();
1138 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
1139 l[strlen(l)-1] = '\0';
1143 Srv->Log(DEBUG,"IN: '"+line+"'");
1144 std::deque<std::string> params = this->Split(line,true);
1145 std::string command = "";
1146 std::string prefix = "";
1147 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
1150 command = params[1];
1151 char* pref = (char*)prefix.c_str();
1159 command = params[0];
1163 switch (this->LinkState)
1168 // Waiting for SERVER command from remote server. Server initiating
1169 // the connection sends the first SERVER command, listening server
1170 // replies with theirs if its happy, then if the initiator is happy,
1171 // it starts to send its net sync, which starts the merge, otherwise
1172 // it sends an ERROR.
1173 if (command == "SERVER")
1175 return this->Inbound_Server(params);
1177 else if (command == "ERROR")
1179 return this->Error(params);
1183 // Waiting for start of other side's netmerge to say they liked our
1185 if (command == "SERVER")
1187 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1191 else if (command == "BURST")
1193 this->LinkState = CONNECTED;
1194 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
1195 TreeRoot->AddChild(Node);
1197 params.push_back(InboundServerName);
1198 params.push_back("*");
1199 params.push_back("1");
1200 params.push_back(":"+InboundDescription);
1201 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
1202 this->DoBurst(Node);
1204 else if (command == "ERROR")
1206 return this->Error(params);
1211 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
1215 if (command == "SERVER")
1217 // another server we connected to, which was in WAIT_AUTH_1 state,
1218 // has just sent us their credentials. If we get this far, theyre
1219 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1220 // if we're happy with this, we should send our netburst which
1221 // kickstarts the merge.
1222 return this->Outbound_Reply_Server(params);
1224 else if (command == "ERROR")
1226 return this->Error(params);
1230 // This is the 'authenticated' state, when all passwords
1231 // have been exchanged and anything past this point is taken
1233 std::string target = "";
1234 if ((command == "NICK") && (params.size() > 1))
1236 return this->IntroduceClient(prefix,params);
1238 else if (command == "FJOIN")
1240 return this->ForceJoin(prefix,params);
1242 else if (command == "SERVER")
1244 return this->RemoteServer(prefix,params);
1246 else if (command == "ERROR")
1248 return this->Error(params);
1250 else if (command == "OPERTYPE")
1252 return this->OperType(prefix,params);
1254 else if (command == "FMODE")
1256 return this->ForceMode(prefix,params);
1258 else if (command == "KILL")
1260 return this->RemoteKill(prefix,params);
1262 else if (command == "FTOPIC")
1264 return this->ForceTopic(prefix,params);
1266 else if (command == "REHASH")
1268 return this->RemoteRehash(prefix,params);
1270 else if (command == "PING")
1272 return this->LocalPing(prefix,params);
1274 else if (command == "PONG")
1276 return this->LocalPong(prefix,params);
1278 else if (command == "VERSION")
1280 return this->ServerVersion(prefix,params);
1282 else if (command == "FHOST")
1284 return this->ChangeHost(prefix,params);
1286 else if (command == "FNAME")
1288 return this->ChangeName(prefix,params);
1290 else if (command == "SQUIT")
1292 if (params.size() == 2)
1294 this->Squit(FindServer(params[0]),params[1]);
1300 // not a special inter-server command.
1301 // Emulate the actual user doing the command,
1302 // this saves us having a huge ugly parser.
1303 userrec* who = Srv->FindNick(prefix);
1304 std::string sourceserv = this->myhost;
1305 if (this->InboundServerName != "")
1307 sourceserv = this->InboundServerName;
1312 target = who->server;
1313 char* strparams[127];
1314 for (unsigned int q = 0; q < params.size(); q++)
1316 strparams[q] = (char*)params[q].c_str();
1318 Srv->CallCommandHandler(command, strparams, params.size(), who);
1322 // its not a user. Its either a server, or somethings screwed up.
1323 if (IsServer(prefix))
1325 target = Srv->GetServerName();
1329 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
1333 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1342 virtual std::string GetName()
1344 std::string sourceserv = this->myhost;
1345 if (this->InboundServerName != "")
1347 sourceserv = this->InboundServerName;
1352 virtual void OnTimeout()
1354 if (this->LinkState == CONNECTING)
1356 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
1360 virtual void OnClose()
1362 // Connection closed.
1363 // If the connection is fully up (state CONNECTED)
1364 // then propogate a netsplit to all peers.
1365 std::string quitserver = this->myhost;
1366 if (this->InboundServerName != "")
1368 quitserver = this->InboundServerName;
1370 TreeServer* s = FindServer(quitserver);
1373 Squit(s,"Remote host closed the connection");
1377 virtual int OnIncomingConnection(int newsock, char* ip)
1379 TreeSocket* s = new TreeSocket(newsock, ip);
1385 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
1387 for (unsigned int c = 0; c < list.size(); c++)
1389 if (list[c] == server)
1394 list.push_back(server);
1397 // returns a list of DIRECT servernames for a specific channel
1398 std::deque<TreeServer*> GetListOfServersForChannel(chanrec* c)
1400 std::deque<TreeServer*> list;
1401 std::vector<char*> *ulist = c->GetUsers();
1402 for (unsigned int i = 0; i < ulist->size(); i++)
1404 char* o = (*ulist)[i];
1405 userrec* otheruser = (userrec*)o;
1406 if (std::string(otheruser->server) != Srv->GetServerName())
1408 TreeServer* best = BestRouteTo(otheruser->server);
1410 AddThisServer(best,list);
1416 bool DoOneToAllButSenderRaw(std::string data,std::string omit,std::string prefix,std::string command,std::deque<std::string> params)
1418 TreeServer* omitroute = BestRouteTo(omit);
1419 if ((command == "NOTICE") || (command == "PRIVMSG"))
1421 if ((params.size() >= 2) && (*(params[0].c_str()) != '$'))
1423 if (*(params[0].c_str()) != '#')
1425 // special routing for private messages/notices
1426 userrec* d = Srv->FindNick(params[0]);
1429 std::deque<std::string> par;
1431 par.push_back(params[0]);
1432 par.push_back(":"+params[1]);
1433 DoOneToOne(prefix,command,par,d->server);
1439 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
1440 chanrec* c = Srv->FindChannel(params[0]);
1443 std::deque<TreeServer*> list = GetListOfServersForChannel(c);
1444 log(DEBUG,"Got a list of %d servers",list.size());
1445 for (unsigned int i = 0; i < list.size(); i++)
1447 TreeSocket* Sock = list[i]->GetSocket();
1448 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
1450 log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
1451 Sock->WriteLine(data);
1459 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1461 TreeServer* Route = TreeRoot->GetChild(x);
1462 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1464 TreeSocket* Sock = Route->GetSocket();
1465 Sock->WriteLine(data);
1471 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit)
1473 TreeServer* omitroute = BestRouteTo(omit);
1474 std::string FullLine = ":" + prefix + " " + command;
1475 for (unsigned int x = 0; x < params.size(); x++)
1477 FullLine = FullLine + " " + params[x];
1479 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1481 TreeServer* Route = TreeRoot->GetChild(x);
1482 // Send the line IF:
1483 // The route has a socket (its a direct connection)
1484 // The route isnt the one to be omitted
1485 // The route isnt the path to the one to be omitted
1486 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1488 TreeSocket* Sock = Route->GetSocket();
1489 Sock->WriteLine(FullLine);
1495 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params)
1497 std::string FullLine = ":" + prefix + " " + command;
1498 for (unsigned int x = 0; x < params.size(); x++)
1500 FullLine = FullLine + " " + params[x];
1502 for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1504 TreeServer* Route = TreeRoot->GetChild(x);
1505 if (Route->GetSocket())
1507 TreeSocket* Sock = Route->GetSocket();
1508 Sock->WriteLine(FullLine);
1514 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target)
1516 TreeServer* Route = BestRouteTo(target);
1519 std::string FullLine = ":" + prefix + " " + command;
1520 for (unsigned int x = 0; x < params.size(); x++)
1522 FullLine = FullLine + " " + params[x];
1524 if (Route->GetSocket())
1526 TreeSocket* Sock = Route->GetSocket();
1527 Sock->WriteLine(FullLine);
1537 std::vector<TreeSocket*> Bindings;
1539 void ReadConfiguration(bool rebind)
1543 for (int j =0; j < Conf->Enumerate("bind"); j++)
1545 std::string Type = Conf->ReadValue("bind","type",j);
1546 std::string IP = Conf->ReadValue("bind","address",j);
1547 long Port = Conf->ReadInteger("bind","port",j,true);
1548 if (Type == "servers")
1554 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
1555 if (listener->GetState() == I_LISTENING)
1557 Srv->AddSocket(listener);
1558 Bindings.push_back(listener);
1562 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
1570 for (int j =0; j < Conf->Enumerate("link"); j++)
1573 L.Name = Conf->ReadValue("link","name",j);
1574 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
1575 L.Port = Conf->ReadInteger("link","port",j,true);
1576 L.SendPass = Conf->ReadValue("link","sendpass",j);
1577 L.RecvPass = Conf->ReadValue("link","recvpass",j);
1578 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
1579 L.NextConnectTime = time(NULL) + L.AutoConnect;
1580 LinkBlocks.push_back(L);
1581 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
1586 class ModuleSpanningTree : public Module
1588 std::vector<TreeSocket*> Bindings;
1594 ModuleSpanningTree()
1597 Conf = new ConfigReader;
1600 // Create the root of the tree
1601 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
1603 ReadConfiguration(true);
1606 void ShowLinks(TreeServer* Current, userrec* user, int hops)
1608 std::string Parent = TreeRoot->GetName();
1609 if (Current->GetParent())
1611 Parent = Current->GetParent()->GetName();
1613 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1615 ShowLinks(Current->GetChild(q),user,hops+1);
1617 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
1620 int CountLocalServs()
1622 return TreeRoot->ChildCount();
1625 void CountServsRecursive(TreeServer* Current)
1628 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1630 CountServsRecursive(Current->GetChild(q));
1637 CountServsRecursive(TreeRoot);
1641 void HandleLinks(char** parameters, int pcnt, userrec* user)
1643 ShowLinks(TreeRoot,user,0);
1644 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
1648 void HandleLusers(char** parameters, int pcnt, userrec* user)
1650 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),this->CountServs());
1651 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
1652 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
1653 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
1654 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
1658 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
1660 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
1664 for (int t = 0; t < depth; t++)
1666 matrix[line][t] = ' ';
1668 strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
1670 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1672 ShowMap(Current->GetChild(q),user,depth+2,matrix);
1677 // Ok, prepare to be confused.
1678 // After much mulling over how to approach this, it struck me that
1679 // the 'usual' way of doing a /MAP isnt the best way. Instead of
1680 // keeping track of a ton of ascii characters, and line by line
1681 // under recursion working out where to place them using multiplications
1682 // and divisons, we instead render the map onto a backplane of characters
1683 // (a character matrix), then draw the branches as a series of "L" shapes
1684 // from the nodes. This is not only friendlier on CPU it uses less stack.
1686 void HandleMap(char** parameters, int pcnt, userrec* user)
1688 // This array represents a virtual screen which we will
1689 // "scratch" draw to, as the console device of an irc
1690 // client does not provide for a proper terminal.
1691 char matrix[128][80];
1692 for (unsigned int t = 0; t < 128; t++)
1694 matrix[t][0] = '\0';
1697 // The only recursive bit is called here.
1698 ShowMap(TreeRoot,user,0,matrix);
1699 // Process each line one by one. The algorithm has a limit of
1700 // 128 servers (which is far more than a spanning tree should have
1701 // anyway, so we're ok). This limit can be raised simply by making
1702 // the character matrix deeper, 128 rows taking 10k of memory.
1703 for (int l = 1; l < line; l++)
1705 // scan across the line looking for the start of the
1706 // servername (the recursive part of the algorithm has placed
1707 // the servers at indented positions depending on what they
1709 int first_nonspace = 0;
1710 while (matrix[l][first_nonspace] == ' ')
1715 // Draw the `- (corner) section: this may be overwritten by
1716 // another L shape passing along the same vertical pane, becoming
1717 // a |- (branch) section instead.
1718 matrix[l][first_nonspace] = '-';
1719 matrix[l][first_nonspace-1] = '`';
1721 // Draw upwards until we hit the parent server, causing possibly
1722 // other corners (`-) to become branches (|-)
1723 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
1725 matrix[l2][first_nonspace-1] = '|';
1729 // dump the whole lot to the user. This is the easy bit, honest.
1730 for (int t = 0; t < line; t++)
1732 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
1734 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
1738 int HandleSquit(char** parameters, int pcnt, userrec* user)
1740 TreeServer* s = FindServerMask(parameters[0]);
1743 TreeSocket* sock = s->GetSocket();
1746 WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
1747 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
1752 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
1757 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
1762 void DoPingChecks(time_t curtime)
1764 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
1766 TreeServer* serv = TreeRoot->GetChild(j);
1767 TreeSocket* sock = serv->GetSocket();
1770 if (curtime >= serv->NextPingTime())
1772 if (serv->AnsweredLastPing())
1774 sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
1775 serv->SetNextPingTime(curtime + 60);
1779 // they didnt answer, boot them
1780 WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
1781 sock->Squit(serv,"Ping timeout");
1790 void AutoConnectServers(time_t curtime)
1792 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1794 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
1796 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
1797 x->NextConnectTime = curtime + x->AutoConnect;
1798 TreeServer* CheckDupe = FindServer(x->Name);
1801 // an autoconnected server is not connected. Check if its time to connect it
1802 WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
1803 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1804 Srv->AddSocket(newsocket);
1810 int HandleVersion(char** parameters, int pcnt, userrec* user)
1812 // we've already checked if pcnt > 0, so this is safe
1813 TreeServer* found = FindServerMask(parameters[0]);
1816 std::string Version = found->GetVersion();
1817 WriteServ(user->fd,"351 %s :%s",user->nick,Version.c_str());
1821 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
1826 int HandleConnect(char** parameters, int pcnt, userrec* user)
1828 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1830 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
1832 TreeServer* CheckDupe = FindServer(x->Name);
1835 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);
1836 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1837 Srv->AddSocket(newsocket);
1842 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());
1847 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
1851 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
1853 if (command == "CONNECT")
1855 return this->HandleConnect(parameters,pcnt,user);
1857 else if (command == "SQUIT")
1859 return this->HandleSquit(parameters,pcnt,user);
1861 else if (command == "MAP")
1863 this->HandleMap(parameters,pcnt,user);
1866 else if (command == "LUSERS")
1868 this->HandleLusers(parameters,pcnt,user);
1871 else if (command == "LINKS")
1873 this->HandleLinks(parameters,pcnt,user);
1876 else if ((command == "VERSION") && (pcnt > 0))
1878 this->HandleVersion(parameters,pcnt,user);
1881 else if (Srv->IsValidModuleCommand(command, pcnt, user))
1883 // this bit of code cleverly routes all module commands
1884 // to all remote severs *automatically* so that modules
1885 // can just handle commands locally, without having
1886 // to have any special provision in place for remote
1887 // commands and linking protocols.
1888 std::deque<std::string> params;
1890 for (int j = 0; j < pcnt; j++)
1892 if (strchr(parameters[j],' '))
1894 params.push_back(":" + std::string(parameters[j]));
1898 params.push_back(std::string(parameters[j]));
1901 DoOneToMany(user->nick,command,params);
1906 virtual void OnGetServerDescription(std::string servername,std::string &description)
1908 TreeServer* s = FindServer(servername);
1911 description = s->GetDesc();
1915 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
1917 if (std::string(source->server) == Srv->GetServerName())
1919 std::deque<std::string> params;
1920 params.push_back(dest->nick);
1921 params.push_back(channel->name);
1922 DoOneToMany(source->nick,"INVITE",params);
1926 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
1928 std::deque<std::string> params;
1929 params.push_back(chan->name);
1930 params.push_back(":"+topic);
1931 DoOneToMany(user->nick,"TOPIC",params);
1934 virtual void OnWallops(userrec* user, std::string text)
1936 if (std::string(user->server) == Srv->GetServerName())
1938 std::deque<std::string> params;
1939 params.push_back(":"+text);
1940 DoOneToMany(user->nick,"WALLOPS",params);
1944 virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
1946 if (target_type == TYPE_USER)
1948 userrec* d = (userrec*)dest;
1949 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1951 std::deque<std::string> params;
1953 params.push_back(d->nick);
1954 params.push_back(":"+text);
1955 DoOneToOne(user->nick,"NOTICE",params,d->server);
1960 if (std::string(user->server) == Srv->GetServerName())
1962 chanrec *c = (chanrec*)dest;
1963 std::deque<TreeServer*> list = GetListOfServersForChannel(c);
1964 for (unsigned int i = 0; i < list.size(); i++)
1966 TreeSocket* Sock = list[i]->GetSocket();
1968 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+std::string(c->name)+" :"+text);
1974 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
1976 if (target_type == TYPE_USER)
1978 // route private messages which are targetted at clients only to the server
1979 // which needs to receive them
1980 userrec* d = (userrec*)dest;
1981 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1983 std::deque<std::string> params;
1985 params.push_back(d->nick);
1986 params.push_back(":"+text);
1987 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
1992 if (std::string(user->server) == Srv->GetServerName())
1994 chanrec *c = (chanrec*)dest;
1995 std::deque<TreeServer*> list = GetListOfServersForChannel(c);
1996 for (unsigned int i = 0; i < list.size(); i++)
1998 TreeSocket* Sock = list[i]->GetSocket();
2000 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+std::string(c->name)+" :"+text);
2006 virtual void OnBackgroundTimer(time_t curtime)
2008 AutoConnectServers(curtime);
2009 DoPingChecks(curtime);
2012 virtual void OnUserJoin(userrec* user, chanrec* channel)
2014 // Only do this for local users
2015 if (std::string(user->server) == Srv->GetServerName())
2017 std::deque<std::string> params;
2019 params.push_back(channel->name);
2022 // if the channel has a key, force the join by emulating the key.
2023 params.push_back(channel->key);
2025 if (channel->GetUserCounter() > 1)
2027 // not the first in the channel
2028 DoOneToMany(user->nick,"JOIN",params);
2032 // first in the channel, set up their permissions
2033 // and the channel TS with FJOIN.
2035 snprintf(ts,24,"%lu",(unsigned long)channel->age);
2037 params.push_back(channel->name);
2038 params.push_back(ts);
2039 params.push_back("@"+std::string(user->nick));
2040 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
2045 virtual void OnChangeHost(userrec* user, std::string newhost)
2047 // only occurs for local clients
2048 std::deque<std::string> params;
2049 params.push_back(newhost);
2050 DoOneToMany(user->nick,"FHOST",params);
2053 virtual void OnChangeName(userrec* user, std::string gecos)
2055 // only occurs for local clients
2056 std::deque<std::string> params;
2057 params.push_back(gecos);
2058 DoOneToMany(user->nick,"FNAME",params);
2061 virtual void OnUserPart(userrec* user, chanrec* channel)
2063 if (std::string(user->server) == Srv->GetServerName())
2065 std::deque<std::string> params;
2067 params.push_back(channel->name);
2068 DoOneToMany(user->nick,"PART",params);
2072 virtual void OnUserConnect(userrec* user)
2074 char agestr[MAXBUF];
2075 if (std::string(user->server) == Srv->GetServerName())
2077 std::deque<std::string> params;
2078 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
2080 params.push_back(agestr);
2081 params.push_back(user->nick);
2082 params.push_back(user->host);
2083 params.push_back(user->dhost);
2084 params.push_back(user->ident);
2085 params.push_back("+"+std::string(user->modes));
2086 params.push_back(user->ip);
2087 params.push_back(":"+std::string(user->fullname));
2088 DoOneToMany(Srv->GetServerName(),"NICK",params);
2092 virtual void OnUserQuit(userrec* user, std::string reason)
2094 if (std::string(user->server) == Srv->GetServerName())
2096 std::deque<std::string> params;
2097 params.push_back(":"+reason);
2098 DoOneToMany(user->nick,"QUIT",params);
2102 virtual void OnUserPostNick(userrec* user, std::string oldnick)
2104 if (std::string(user->server) == Srv->GetServerName())
2106 std::deque<std::string> params;
2107 params.push_back(user->nick);
2108 DoOneToMany(oldnick,"NICK",params);
2112 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
2114 if (std::string(source->server) == Srv->GetServerName())
2116 std::deque<std::string> params;
2117 params.push_back(chan->name);
2118 params.push_back(user->nick);
2119 params.push_back(":"+reason);
2120 DoOneToMany(source->nick,"KICK",params);
2124 virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
2126 std::deque<std::string> params;
2127 params.push_back(dest->nick);
2128 params.push_back(":"+reason);
2129 DoOneToMany(source->nick,"KILL",params);
2132 virtual void OnRehash(std::string parameter)
2134 if (parameter != "")
2136 std::deque<std::string> params;
2137 params.push_back(parameter);
2138 DoOneToMany(Srv->GetServerName(),"REHASH",params);
2140 if (Srv->MatchText(Srv->GetServerName(),parameter))
2142 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
2143 Srv->RehashServer();
2146 ReadConfiguration(false);
2149 // note: the protocol does not allow direct umode +o except
2150 // via NICK with 8 params. sending OPERTYPE infers +o modechange
2152 virtual void OnOper(userrec* user, std::string opertype)
2154 if (std::string(user->server) == Srv->GetServerName())
2156 std::deque<std::string> params;
2157 params.push_back(opertype);
2158 DoOneToMany(user->nick,"OPERTYPE",params);
2162 virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
2164 if (std::string(user->server) == Srv->GetServerName())
2166 if (target_type == TYPE_USER)
2168 userrec* u = (userrec*)dest;
2169 std::deque<std::string> params;
2170 params.push_back(u->nick);
2171 params.push_back(text);
2172 DoOneToMany(user->nick,"MODE",params);
2176 chanrec* c = (chanrec*)dest;
2177 std::deque<std::string> params;
2178 params.push_back(c->name);
2179 params.push_back(text);
2180 DoOneToMany(user->nick,"MODE",params);
2185 virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
2187 TreeSocket* s = (TreeSocket*)opaque;
2190 if (target_type == TYPE_USER)
2192 userrec* u = (userrec*)target;
2193 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
2197 chanrec* c = (chanrec*)target;
2198 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
2203 virtual ~ModuleSpanningTree()
2208 virtual Version GetVersion()
2210 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
2215 class ModuleSpanningTreeFactory : public ModuleFactory
2218 ModuleSpanningTreeFactory()
2222 ~ModuleSpanningTreeFactory()
2226 virtual Module * CreateModule()
2228 TreeProtocolModule = new ModuleSpanningTree;
2229 return TreeProtocolModule;
2235 extern "C" void * init_module( void )
2237 return new ModuleSpanningTreeFactory;