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 * ---------------------------------------------------
17 /* $ModDesc: Povides a spanning tree server link protocol */
25 #include "inspircd_config.h"
27 #include <ext/hash_map>
35 #include "helperfuncs.h"
37 #include "inspstring.h"
43 #define nspace __gnu_cxx
48 class ModuleSpanningTree;
49 static ModuleSpanningTree* TreeProtocolModule;
51 extern std::vector<Module*> modules;
52 extern std::vector<ircd_module*> factory;
55 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
57 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
58 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;
60 extern user_hash clientlist;
61 extern chan_hash chanlist;
68 typedef nspace::hash_map<std::string, TreeServer*> server_hash;
69 server_hash serverlist;
71 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target);
72 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit);
73 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params);
74 bool DoOneToAllButSenderRaw(std::string data,std::string omit, std::string prefix,std::string command,std::deque<std::string> params);
75 void ReadConfiguration(bool rebind);
81 std::vector<TreeServer*> Children;
82 std::string ServerName;
83 std::string ServerDesc;
84 std::string VersionString;
87 TreeSocket* Socket; // for directly connected servers this points at the socket object
99 UserCount = OperCount = 0;
100 VersionString = GetVersionString();
103 TreeServer(std::string Name, std::string Desc) : ServerName(Name), ServerDesc(Desc)
107 UserCount = OperCount = 0;
108 VersionString = GetVersionString();
113 TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name), ServerDesc(Desc), Socket(Sock)
116 UserCount = OperCount = 0;
117 this->SetNextPingTime(time(NULL) + 60);
120 /* find the 'route' for this server (e.g. the one directly connected
121 * to the local server, which we can use to reach it)
123 * In the following example, consider we have just added a TreeServer
124 * class for server G on our network, of which we are server A.
125 * To route traffic to G (marked with a *) we must send the data to
126 * B (marked with a +) so this algorithm initializes the 'Route'
127 * value to point at whichever server traffic must be routed through
128 * to get here. If we were to try this algorithm with server B,
129 * the Route pointer would point at its own object ('this').
139 * We only run this algorithm when a server is created, as
140 * the routes remain constant while ever the server exists, and
141 * do not need to be re-calculated.
145 if (Route == TreeRoot)
151 while (this->Route->GetParent() != TreeRoot)
153 this->Route = Route->GetParent();
157 /* Because recursive code is slow and takes a lot of resources,
158 * we store two representations of the server tree. The first
159 * is a recursive structure where each server references its
160 * children and its parent, which is used for netbursts and
161 * netsplits to dump the whole dataset to the other server,
162 * and the second is used for very fast lookups when routing
163 * messages and is instead a hash_map, where each item can
164 * be referenced by its server name. The AddHashEntry()
165 * call below automatically inserts each TreeServer class
166 * into the hash_map as it is created. There is a similar
167 * maintainance call in the destructor to tidy up deleted
171 this->AddHashEntry();
176 server_hash::iterator iter;
177 iter = serverlist.find(this->ServerName);
178 if (iter == serverlist.end())
179 serverlist[this->ServerName] = this;
184 server_hash::iterator iter;
185 iter = serverlist.find(this->ServerName);
186 if (iter != serverlist.end())
187 serverlist.erase(iter);
190 TreeServer* GetRoute()
195 std::string GetName()
197 return this->ServerName;
200 std::string GetDesc()
202 return this->ServerDesc;
205 std::string GetVersion()
207 return this->VersionString;
210 void SetNextPingTime(time_t t)
213 LastPingWasGood = false;
216 time_t NextPingTime()
218 return this->NextPing;
221 bool AnsweredLastPing()
223 return LastPingWasGood;
228 LastPingWasGood = true;
233 return this->UserCount;
238 return this->OperCount;
241 TreeSocket* GetSocket()
246 TreeServer* GetParent()
251 void SetVersion(std::string Version)
253 VersionString = Version;
256 unsigned int ChildCount()
258 return Children.size();
261 TreeServer* GetChild(unsigned int n)
263 if (n < Children.size())
273 void AddChild(TreeServer* Child)
275 Children.push_back(Child);
278 bool DelChild(TreeServer* Child)
280 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
291 /* Removes child nodes of this node, and of that node, etc etc.
292 * This is used during netsplits to automatically tidy up the
293 * server tree. It is slow, we don't use it for much else.
297 bool stillchildren = true;
298 while (stillchildren)
300 stillchildren = false;
301 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
303 TreeServer* s = (TreeServer*)*a;
307 stillchildren = true;
316 this->DelHashEntry();
326 std::string SendPass;
327 std::string RecvPass;
328 unsigned long AutoConnect;
329 time_t NextConnectTime;
334 std::vector<Link> LinkBlocks;
336 TreeServer* FindServer(std::string ServerName)
338 server_hash::iterator iter;
339 iter = serverlist.find(ServerName);
340 if (iter != serverlist.end())
350 /* Returns the locally connected server we must route a
351 * message through to reach server 'ServerName'. This
352 * only applies to one-to-one and not one-to-many routing.
353 * See the comments for the constructor of TreeServer
356 TreeServer* BestRouteTo(std::string ServerName)
358 if (ServerName.c_str() == TreeRoot->GetName())
360 TreeServer* Found = FindServer(ServerName);
363 return Found->GetRoute();
373 /* TODO: These need optimizing to use an iterator of serverlist
375 void RFindServerMask(TreeServer* Current, std::string ServerName)
377 if (Srv->MatchText(Current->GetName(),ServerName) && (!Found))
384 for (unsigned int q = 0; q < Current->ChildCount(); q++)
387 RFindServerMask(Current->GetChild(q),ServerName);
392 TreeServer* FindServerMask(std::string ServerName)
395 RFindServerMask(TreeRoot,ServerName);
399 bool IsServer(std::string ServerName)
401 return (FindServer(ServerName) != NULL);
404 class TreeSocket : public InspSocket
407 std::string in_buffer;
408 ServerState LinkState;
409 std::string InboundServerName;
410 std::string InboundDescription;
412 int num_lost_servers;
414 bool LastPingWasGood;
418 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
419 : InspSocket(host, port, listening, maxtime)
422 this->LinkState = LISTENER;
425 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
426 : InspSocket(host, port, listening, maxtime)
429 this->LinkState = CONNECTING;
432 TreeSocket(int newfd, char* ip)
433 : InspSocket(newfd, ip)
435 this->LinkState = WAIT_AUTH_1;
438 virtual bool OnConnected()
440 if (this->LinkState == CONNECTING)
442 Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
443 // we should send our details here.
444 // if the other side is satisfied, they send theirs.
445 // we do not need to change state here.
446 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
448 if (x->Name == this->myhost)
450 // found who we're supposed to be connecting to, send the neccessary gubbins.
451 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
459 virtual void OnError(InspSocketError e)
463 virtual int OnDisconnect()
468 // recursively send the server tree with distances as hops
469 void SendServers(TreeServer* Current, TreeServer* s, int hops)
472 for (unsigned int q = 0; q < Current->ChildCount(); q++)
474 TreeServer* recursive_server = Current->GetChild(q);
475 if (recursive_server != s)
477 // :source.server SERVER server.name hops :Description
478 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
479 this->WriteLine(command);
480 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
481 // down to next level
482 this->SendServers(recursive_server, s, hops+1);
487 void SquitServer(TreeServer* Current)
489 // recursively squit the servers attached to 'Current'
490 for (unsigned int q = 0; q < Current->ChildCount(); q++)
492 TreeServer* recursive_server = Current->GetChild(q);
493 this->SquitServer(recursive_server);
495 // Now we've whacked the kids, whack self
497 bool quittingpeople = true;
498 while (quittingpeople)
500 quittingpeople = false;
501 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
503 if (!strcasecmp(u->second->server,Current->GetName().c_str()))
505 Srv->QuitUser(u->second,Current->GetName()+" "+std::string(Srv->GetServerName()));
507 quittingpeople = true;
514 void Squit(TreeServer* Current,std::string reason)
518 std::deque<std::string> params;
519 params.push_back(Current->GetName());
520 params.push_back(":"+reason);
521 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
522 if (Current->GetParent() == TreeRoot)
524 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
528 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
530 num_lost_servers = 0;
532 SquitServer(Current);
534 Current->GetParent()->DelChild(Current);
536 WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
540 log(DEFAULT,"Squit from unknown server");
544 bool ForceMode(std::string source, std::deque<std::string> params)
546 userrec* who = new userrec;
547 who->fd = FD_MAGIC_NUMBER;
548 if (params.size() < 2)
551 for (unsigned int q = 0; q < params.size(); q++)
553 modelist[q] = (char*)params[q].c_str();
555 Srv->SendMode(modelist,params.size(),who);
556 DoOneToAllButSender(source,"FMODE",params,source);
561 bool ForceTopic(std::string source, std::deque<std::string> params)
563 // FTOPIC %s %lu %s :%s
564 if (params.size() != 4)
566 std::string channel = params[0];
567 time_t ts = atoi(params[1].c_str());
568 std::string setby = params[2];
569 std::string topic = params[3];
571 chanrec* c = Srv->FindChannel(channel);
574 if ((ts >= c->topicset) || (!*c->topic))
576 std::string oldtopic = c->topic;
577 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
578 strlcpy(c->setby,setby.c_str(),NICKMAX);
580 // if the topic text is the same as the current topic,
581 // dont bother to send the TOPIC command out, just silently
582 // update the set time and set nick.
583 if (oldtopic != topic)
584 WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
589 // all done, send it on its way
590 params[3] = ":" + params[3];
591 DoOneToAllButSender(source,"FTOPIC",params,source);
596 bool ForceJoin(std::string source, std::deque<std::string> params)
598 if (params.size() < 3)
602 char modestring[MAXBUF];
603 char* mode_users[127];
604 mode_users[0] = first;
605 mode_users[1] = modestring;
606 strcpy(mode_users[1],"+");
607 unsigned int modectr = 2;
610 std::string channel = params[0];
611 time_t TS = atoi(params[1].c_str());
614 chanrec* chan = Srv->FindChannel(channel);
619 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
621 // default is a high value, which if we dont have this
622 // channel will let the other side apply their modes.
623 time_t ourTS = time(NULL)+600;
624 chanrec* us = Srv->FindChannel(channel);
630 log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
632 // do this first, so our mode reversals are correctly received by other servers
633 // if there is a TS collision.
634 DoOneToAllButSender(source,"FJOIN",params,source);
636 for (unsigned int usernum = 2; usernum < params.size(); usernum++)
638 // process one channel at a time, applying modes.
639 char* usr = (char*)params[usernum].c_str();
640 char permissions = *usr;
645 mode_users[modectr++] = usr;
646 strlcat(modestring,"o",MAXBUF);
650 mode_users[modectr++] = usr;
651 strlcat(modestring,"h",MAXBUF);
655 mode_users[modectr++] = usr;
656 strlcat(modestring,"v",MAXBUF);
659 who = Srv->FindNick(usr);
662 Srv->JoinUserToChannel(who,channel,key);
663 if (modectr >= (MAXMODES-1))
665 // theres a mode for this user. push them onto the mode queue, and flush it
666 // if there are more than MAXMODES to go.
669 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
670 Srv->SendMode(mode_users,modectr,who);
674 log(DEBUG,"Their channel newer than ours, bouncing their modes");
676 std::deque<std::string> params;
677 // modes are now being UNSET...
678 *mode_users[1] = '-';
679 for (unsigned int x = 0; x < modectr; x++)
681 params.push_back(mode_users[x]);
683 // tell everyone to bounce the modes. bad modes, bad!
684 DoOneToMany(Srv->GetServerName(),"FMODE",params);
686 strcpy(mode_users[1],"+");
691 // there werent enough modes built up to flush it during FJOIN,
692 // or, there are a number left over. flush them out.
693 if ((modectr > 2) && (who))
697 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
698 Srv->SendMode(mode_users,modectr,who);
702 log(DEBUG,"Their channel newer than ours, bouncing their modes");
703 std::deque<std::string> params;
704 *mode_users[1] = '-';
705 for (unsigned int x = 0; x < modectr; x++)
707 params.push_back(mode_users[x]);
709 DoOneToMany(Srv->GetServerName(),"FMODE",params);
715 bool IntroduceClient(std::string source, std::deque<std::string> params)
717 if (params.size() < 8)
719 // NICK age nick host dhost ident +modes ip :gecos
721 std::string nick = params[1];
722 std::string host = params[2];
723 std::string dhost = params[3];
724 std::string ident = params[4];
725 time_t age = atoi(params[0].c_str());
726 std::string modes = params[5];
727 while (*(modes.c_str()) == '+')
729 char* m = (char*)modes.c_str();
733 std::string ip = params[6];
734 std::string gecos = params[7];
735 char* tempnick = (char*)nick.c_str();
736 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
738 user_hash::iterator iter;
739 iter = clientlist.find(tempnick);
740 if (iter != clientlist.end())
743 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);
744 this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
748 clientlist[tempnick] = new userrec();
749 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
750 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
751 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
752 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
753 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
754 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
755 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
756 clientlist[tempnick]->registered = 7;
757 clientlist[tempnick]->signon = age;
758 strlcpy(clientlist[tempnick]->modes, modes.c_str(),53);
759 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
760 for (int i = 0; i < MAXCHANS; i++)
762 clientlist[tempnick]->chans[i].channel = NULL;
763 clientlist[tempnick]->chans[i].uc_modes = 0;
765 params[7] = ":" + params[7];
766 DoOneToAllButSender(source,"NICK",params,source);
770 void SendFJoins(TreeServer* Current, chanrec* c)
773 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
774 std::vector<char*> *ulist = c->GetUsers();
775 for (unsigned int i = 0; i < ulist->size(); i++)
777 char* o = (*ulist)[i];
778 userrec* otheruser = (userrec*)o;
779 strlcat(list," ",MAXBUF);
780 strlcat(list,cmode(otheruser,c),MAXBUF);
781 strlcat(list,otheruser->nick,MAXBUF);
782 if (strlen(list)>(480-NICKMAX))
784 this->WriteLine(list);
785 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
788 if (list[strlen(list)-1] != ':')
790 this->WriteLine(list);
794 void SendXLines(TreeServer* Current)
797 // for zlines and qlines, we should first check if theyre global...
798 for (std::vector<ZLine>::iterator i = zlines.begin(); i != zlines.end(); i++)
800 snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->ipaddr,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
801 this->WriteLine(data);
803 for (std::vector<QLine>::iterator i = qlines.begin(); i != qlines.end(); i++)
805 snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->nick,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
806 this->WriteLine(data);
808 for (std::vector<GLine>::iterator i = glines.begin(); i != glines.end(); i++)
810 snprintf(data,MAXBUF,":%s ADDLINE G %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
811 this->WriteLine(data);
813 for (std::vector<ELine>::iterator i = elines.begin(); i != elines.end(); i++)
815 snprintf(data,MAXBUF,":%s ADDLINE E %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
816 this->WriteLine(data);
820 void SendChannelModes(TreeServer* Current)
823 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
825 SendFJoins(Current, c->second);
826 snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
827 this->WriteLine(data);
828 if (*c->second->topic)
830 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);
831 this->WriteLine(data);
833 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
835 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
836 this->WriteLine(data);
838 FOREACH_MOD OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this);
842 // send all users and their channels
843 void SendUsers(TreeServer* Current)
846 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
848 if (u->second->registered == 7)
850 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);
851 this->WriteLine(data);
852 if (strchr(u->second->modes,'o'))
854 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
856 //char* chl = chlist(u->second,u->second);
859 // this->WriteLine(":"+std::string(u->second->nick)+" FJOIN "+std::string(chl));
861 FOREACH_MOD OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this);
866 void DoBurst(TreeServer* s)
868 Srv->SendOpers("*** Bursting to "+s->GetName()+".");
869 this->WriteLine("BURST");
870 // send our version string
871 this->WriteLine(":"+Srv->GetServerName()+" VERSION :"+GetVersionString());
873 this->SendServers(TreeRoot,s,1);
874 // Send users and their channels
876 // Send everything else (channel modes etc)
877 this->SendChannelModes(s);
879 this->WriteLine("ENDBURST");
882 virtual bool OnDataReady()
884 char* data = this->Read();
887 this->in_buffer += data;
888 while (in_buffer.find("\n") != std::string::npos)
890 char* line = (char*)in_buffer.c_str();
891 std::string ret = "";
892 while ((*line != '\n') && (strlen(line)))
897 if ((*line == '\n') || (*line == '\r'))
900 if (!this->ProcessLine(ret))
906 return (data != NULL);
909 int WriteLine(std::string line)
911 return this->Write(line + "\r\n");
914 bool Error(std::deque<std::string> params)
916 if (params.size() < 1)
918 std::string Errmsg = params[0];
919 std::string SName = myhost;
920 if (InboundServerName != "")
922 SName = InboundServerName;
924 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
925 // we will return false to cause the socket to close.
929 bool OperType(std::string prefix, std::deque<std::string> params)
931 if (params.size() != 1)
933 std::string opertype = params[0];
934 userrec* u = Srv->FindNick(prefix);
937 strlcpy(u->oper,opertype.c_str(),NICKMAX);
938 if (!strchr(u->modes,'o'))
940 strcat(u->modes,"o");
942 DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
947 bool RemoteRehash(std::string prefix, std::deque<std::string> params)
949 if (params.size() < 1)
951 std::string servermask = params[0];
952 if (Srv->MatchText(Srv->GetServerName(),servermask))
954 Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
956 ReadConfiguration(false);
958 DoOneToAllButSender(prefix,"REHASH",params,prefix);
962 bool RemoteKill(std::string prefix, std::deque<std::string> params)
964 if (params.size() != 2)
966 std::string nick = params[0];
967 std::string reason = params[1];
968 userrec* u = Srv->FindNick(prefix);
969 userrec* who = Srv->FindNick(nick);
972 std::string sourceserv = prefix;
975 sourceserv = u->server;
977 params[1] = ":" + params[1];
978 DoOneToAllButSender(prefix,"KILL",params,sourceserv);
979 Srv->QuitUser(who,reason);
984 bool LocalPong(std::string prefix, std::deque<std::string> params)
986 if (params.size() < 1)
988 TreeServer* ServerSource = FindServer(prefix);
991 ServerSource->SetPingFlag();
996 bool ServerVersion(std::string prefix, std::deque<std::string> params)
998 if (params.size() < 1)
1000 TreeServer* ServerSource = FindServer(prefix);
1003 ServerSource->SetVersion(params[0]);
1005 params[0] = ":" + params[0];
1006 DoOneToAllButSender(prefix,"VERSION",params,prefix);
1010 bool ChangeHost(std::string prefix, std::deque<std::string> params)
1012 if (params.size() < 1)
1014 userrec* u = Srv->FindNick(prefix);
1017 Srv->ChangeHost(u,params[0]);
1018 DoOneToAllButSender(prefix,"FHOST",params,u->server);
1023 bool AddLine(std::string prefix, std::deque<std::string> params)
1025 if (params.size() < 6)
1027 std::string linetype = params[0]; /* Z, Q, E, G, K */
1028 std::string mask = params[1]; /* Line type dependent */
1029 std::string source = params[2]; /* may not be online or may be a server */
1030 std::string settime = params[3]; /* EPOCH time set */
1031 std::string duration = params[4]; /* Duration secs */
1032 std::string reason = params[5];
1034 switch (*(linetype.c_str()))
1037 add_zline(atoi(duration), source.c_str(), reason.c_str(), mask.c_str());
1040 add_qline(atoi(duration), source.c_str(), reason.c_str(), mask.c_str());
1043 add_eline(atoi(duration), source.c_str(), reason.c_str(), mask.c_str());
1046 add_gline(atoi(duration), source.c_str(), reason.c_str(), mask.c_str());
1049 add_kline(atoi(duration), source.c_str(), reason.c_str(), mask.c_str());
1052 /* Just in case... */
1053 Srv->SendOpers("*** \2WARNING\2: Invalid xline type '"+linetype+"' sent by server "+prefix+", ignored!")
1056 /* Send it on its way */
1057 params[5] = ":" + params[5];
1058 DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
1062 bool ChangeName(std::string prefix, std::deque<std::string> params)
1064 if (params.size() < 1)
1066 userrec* u = Srv->FindNick(prefix);
1069 Srv->ChangeGECOS(u,params[0]);
1070 params[0] = ":" + params[0];
1071 DoOneToAllButSender(prefix,"FNAME",params,u->server);
1076 bool LocalPing(std::string prefix, std::deque<std::string> params)
1078 if (params.size() < 1)
1080 std::string stufftobounce = params[0];
1081 this->WriteLine(":"+Srv->GetServerName()+" PONG "+stufftobounce);
1085 bool RemoteServer(std::string prefix, std::deque<std::string> params)
1087 if (params.size() < 4)
1089 std::string servername = params[0];
1090 std::string password = params[1];
1091 // hopcount is not used for a remote server, we calculate this ourselves
1092 std::string description = params[3];
1093 TreeServer* ParentOfThis = FindServer(prefix);
1096 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
1099 TreeServer* CheckDupe = FindServer(servername);
1102 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1105 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
1106 ParentOfThis->AddChild(Node);
1107 params[3] = ":" + params[3];
1108 DoOneToAllButSender(prefix,"SERVER",params,prefix);
1109 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
1113 bool Outbound_Reply_Server(std::deque<std::string> params)
1115 if (params.size() < 4)
1117 std::string servername = params[0];
1118 std::string password = params[1];
1119 int hops = atoi(params[2].c_str());
1122 this->WriteLine("ERROR :Server too far away for authentication");
1125 std::string description = params[3];
1126 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1128 if ((x->Name == servername) && (x->RecvPass == password))
1130 TreeServer* CheckDupe = FindServer(servername);
1133 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1136 // Begin the sync here. this kickstarts the
1137 // other side, waiting in WAIT_AUTH_2 state,
1138 // into starting their burst, as it shows
1139 // that we're happy.
1140 this->LinkState = CONNECTED;
1141 // we should add the details of this server now
1142 // to the servers tree, as a child of the root
1144 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
1145 TreeRoot->AddChild(Node);
1146 params[3] = ":" + params[3];
1147 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
1148 this->DoBurst(Node);
1152 this->WriteLine("ERROR :Invalid credentials");
1156 bool Inbound_Server(std::deque<std::string> params)
1158 if (params.size() < 4)
1160 std::string servername = params[0];
1161 std::string password = params[1];
1162 int hops = atoi(params[2].c_str());
1165 this->WriteLine("ERROR :Server too far away for authentication");
1168 std::string description = params[3];
1169 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1171 if ((x->Name == servername) && (x->RecvPass == password))
1173 TreeServer* CheckDupe = FindServer(servername);
1176 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1179 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
1180 this->InboundServerName = servername;
1181 this->InboundDescription = description;
1182 // this is good. Send our details: Our server name and description and hopcount of 0,
1183 // along with the sendpass from this block.
1184 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
1185 // move to the next state, we are now waiting for THEM.
1186 this->LinkState = WAIT_AUTH_2;
1190 this->WriteLine("ERROR :Invalid credentials");
1194 std::deque<std::string> Split(std::string line, bool stripcolon)
1196 std::deque<std::string> n;
1197 if (!strchr(line.c_str(),' '))
1202 std::stringstream s(line);
1203 std::string param = "";
1222 if ((param == ":") && (item > 0))
1245 bool ProcessLine(std::string line)
1247 char* l = (char*)line.c_str();
1248 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
1249 l[strlen(l)-1] = '\0';
1253 Srv->Log(DEBUG,"IN: '"+line+"'");
1254 std::deque<std::string> params = this->Split(line,true);
1255 std::string command = "";
1256 std::string prefix = "";
1257 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
1260 command = params[1];
1261 char* pref = (char*)prefix.c_str();
1269 command = params[0];
1273 switch (this->LinkState)
1278 // Waiting for SERVER command from remote server. Server initiating
1279 // the connection sends the first SERVER command, listening server
1280 // replies with theirs if its happy, then if the initiator is happy,
1281 // it starts to send its net sync, which starts the merge, otherwise
1282 // it sends an ERROR.
1283 if (command == "SERVER")
1285 return this->Inbound_Server(params);
1287 else if (command == "ERROR")
1289 return this->Error(params);
1293 // Waiting for start of other side's netmerge to say they liked our
1295 if (command == "SERVER")
1297 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1301 else if (command == "BURST")
1303 this->LinkState = CONNECTED;
1304 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
1305 TreeRoot->AddChild(Node);
1307 params.push_back(InboundServerName);
1308 params.push_back("*");
1309 params.push_back("1");
1310 params.push_back(":"+InboundDescription);
1311 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
1312 this->DoBurst(Node);
1314 else if (command == "ERROR")
1316 return this->Error(params);
1321 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
1325 if (command == "SERVER")
1327 // another server we connected to, which was in WAIT_AUTH_1 state,
1328 // has just sent us their credentials. If we get this far, theyre
1329 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1330 // if we're happy with this, we should send our netburst which
1331 // kickstarts the merge.
1332 return this->Outbound_Reply_Server(params);
1334 else if (command == "ERROR")
1336 return this->Error(params);
1340 // This is the 'authenticated' state, when all passwords
1341 // have been exchanged and anything past this point is taken
1343 std::string target = "";
1344 if ((command == "NICK") && (params.size() > 1))
1346 return this->IntroduceClient(prefix,params);
1348 else if (command == "FJOIN")
1350 return this->ForceJoin(prefix,params);
1352 else if (command == "SERVER")
1354 return this->RemoteServer(prefix,params);
1356 else if (command == "ERROR")
1358 return this->Error(params);
1360 else if (command == "OPERTYPE")
1362 return this->OperType(prefix,params);
1364 else if (command == "FMODE")
1366 return this->ForceMode(prefix,params);
1368 else if (command == "KILL")
1370 return this->RemoteKill(prefix,params);
1372 else if (command == "FTOPIC")
1374 return this->ForceTopic(prefix,params);
1376 else if (command == "REHASH")
1378 return this->RemoteRehash(prefix,params);
1380 else if (command == "PING")
1382 return this->LocalPing(prefix,params);
1384 else if (command == "PONG")
1386 return this->LocalPong(prefix,params);
1388 else if (command == "VERSION")
1390 return this->ServerVersion(prefix,params);
1392 else if (command == "FHOST")
1394 return this->ChangeHost(prefix,params);
1396 else if (command == "FNAME")
1398 return this->ChangeName(prefix,params);
1400 else if (command == "ADDLINE")
1402 return this->AddLine(prefix,params);
1404 else if (command == "SQUIT")
1406 if (params.size() == 2)
1408 this->Squit(FindServer(params[0]),params[1]);
1414 // not a special inter-server command.
1415 // Emulate the actual user doing the command,
1416 // this saves us having a huge ugly parser.
1417 userrec* who = Srv->FindNick(prefix);
1418 std::string sourceserv = this->myhost;
1419 if (this->InboundServerName != "")
1421 sourceserv = this->InboundServerName;
1426 target = who->server;
1427 char* strparams[127];
1428 for (unsigned int q = 0; q < params.size(); q++)
1430 strparams[q] = (char*)params[q].c_str();
1432 Srv->CallCommandHandler(command, strparams, params.size(), who);
1436 // its not a user. Its either a server, or somethings screwed up.
1437 if (IsServer(prefix))
1439 target = Srv->GetServerName();
1443 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
1447 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1456 virtual std::string GetName()
1458 std::string sourceserv = this->myhost;
1459 if (this->InboundServerName != "")
1461 sourceserv = this->InboundServerName;
1466 virtual void OnTimeout()
1468 if (this->LinkState == CONNECTING)
1470 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
1474 virtual void OnClose()
1476 // Connection closed.
1477 // If the connection is fully up (state CONNECTED)
1478 // then propogate a netsplit to all peers.
1479 std::string quitserver = this->myhost;
1480 if (this->InboundServerName != "")
1482 quitserver = this->InboundServerName;
1484 TreeServer* s = FindServer(quitserver);
1487 Squit(s,"Remote host closed the connection");
1491 virtual int OnIncomingConnection(int newsock, char* ip)
1493 TreeSocket* s = new TreeSocket(newsock, ip);
1499 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
1501 for (unsigned int c = 0; c < list.size(); c++)
1503 if (list[c] == server)
1508 list.push_back(server);
1511 // returns a list of DIRECT servernames for a specific channel
1512 void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
1514 std::vector<char*> *ulist = c->GetUsers();
1515 unsigned int ucount = ulist->size();
1516 for (unsigned int i = 0; i < ucount; i++)
1518 char* o = (*ulist)[i];
1519 userrec* otheruser = (userrec*)o;
1520 if (std::string(otheruser->server) != Srv->GetServerName())
1522 TreeServer* best = BestRouteTo(otheruser->server);
1524 AddThisServer(best,list);
1530 bool DoOneToAllButSenderRaw(std::string data,std::string omit,std::string prefix,std::string command,std::deque<std::string> params)
1532 TreeServer* omitroute = BestRouteTo(omit);
1533 if ((command == "NOTICE") || (command == "PRIVMSG"))
1535 if ((params.size() >= 2) && (*(params[0].c_str()) != '$'))
1537 if (*(params[0].c_str()) != '#')
1539 // special routing for private messages/notices
1540 userrec* d = Srv->FindNick(params[0]);
1543 std::deque<std::string> par;
1544 par.push_back(params[0]);
1545 par.push_back(":"+params[1]);
1546 DoOneToOne(prefix,command,par,d->server);
1552 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
1553 chanrec* c = Srv->FindChannel(params[0]);
1556 std::deque<TreeServer*> list;
1557 GetListOfServersForChannel(c,list);
1558 log(DEBUG,"Got a list of %d servers",list.size());
1559 unsigned int lsize = list.size();
1560 for (unsigned int i = 0; i < lsize; i++)
1562 TreeSocket* Sock = list[i]->GetSocket();
1563 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
1565 log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
1566 Sock->WriteLine(data);
1574 unsigned int items = TreeRoot->ChildCount();
1575 for (unsigned int x = 0; x < items; x++)
1577 TreeServer* Route = TreeRoot->GetChild(x);
1578 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1580 TreeSocket* Sock = Route->GetSocket();
1581 Sock->WriteLine(data);
1587 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit)
1589 TreeServer* omitroute = BestRouteTo(omit);
1590 std::string FullLine = ":" + prefix + " " + command;
1591 unsigned int words = params.size();
1592 for (unsigned int x = 0; x < words; x++)
1594 FullLine = FullLine + " " + params[x];
1596 unsigned int items = TreeRoot->ChildCount();
1597 for (unsigned int x = 0; x < items; x++)
1599 TreeServer* Route = TreeRoot->GetChild(x);
1600 // Send the line IF:
1601 // The route has a socket (its a direct connection)
1602 // The route isnt the one to be omitted
1603 // The route isnt the path to the one to be omitted
1604 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1606 TreeSocket* Sock = Route->GetSocket();
1607 Sock->WriteLine(FullLine);
1613 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params)
1615 std::string FullLine = ":" + prefix + " " + command;
1616 unsigned int words = params.size();
1617 for (unsigned int x = 0; x < words; x++)
1619 FullLine = FullLine + " " + params[x];
1621 unsigned int items = TreeRoot->ChildCount();
1622 for (unsigned int x = 0; x < items; x++)
1624 TreeServer* Route = TreeRoot->GetChild(x);
1625 if (Route->GetSocket())
1627 TreeSocket* Sock = Route->GetSocket();
1628 Sock->WriteLine(FullLine);
1634 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target)
1636 TreeServer* Route = BestRouteTo(target);
1639 std::string FullLine = ":" + prefix + " " + command;
1640 unsigned int words = params.size();
1641 for (unsigned int x = 0; x < words; x++)
1643 FullLine = FullLine + " " + params[x];
1645 if (Route->GetSocket())
1647 TreeSocket* Sock = Route->GetSocket();
1648 Sock->WriteLine(FullLine);
1658 std::vector<TreeSocket*> Bindings;
1660 void ReadConfiguration(bool rebind)
1664 for (int j =0; j < Conf->Enumerate("bind"); j++)
1666 std::string Type = Conf->ReadValue("bind","type",j);
1667 std::string IP = Conf->ReadValue("bind","address",j);
1668 long Port = Conf->ReadInteger("bind","port",j,true);
1669 if (Type == "servers")
1675 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
1676 if (listener->GetState() == I_LISTENING)
1678 Srv->AddSocket(listener);
1679 Bindings.push_back(listener);
1683 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
1691 for (int j =0; j < Conf->Enumerate("link"); j++)
1694 L.Name = Conf->ReadValue("link","name",j);
1695 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
1696 L.Port = Conf->ReadInteger("link","port",j,true);
1697 L.SendPass = Conf->ReadValue("link","sendpass",j);
1698 L.RecvPass = Conf->ReadValue("link","recvpass",j);
1699 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
1700 L.NextConnectTime = time(NULL) + L.AutoConnect;
1701 LinkBlocks.push_back(L);
1702 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
1707 class ModuleSpanningTree : public Module
1709 std::vector<TreeSocket*> Bindings;
1715 ModuleSpanningTree()
1718 Conf = new ConfigReader;
1721 // Create the root of the tree
1722 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
1724 ReadConfiguration(true);
1727 void ShowLinks(TreeServer* Current, userrec* user, int hops)
1729 std::string Parent = TreeRoot->GetName();
1730 if (Current->GetParent())
1732 Parent = Current->GetParent()->GetName();
1734 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1736 ShowLinks(Current->GetChild(q),user,hops+1);
1738 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
1741 int CountLocalServs()
1743 return TreeRoot->ChildCount();
1746 void CountServsRecursive(TreeServer* Current)
1749 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1751 CountServsRecursive(Current->GetChild(q));
1758 CountServsRecursive(TreeRoot);
1762 void HandleLinks(char** parameters, int pcnt, userrec* user)
1764 ShowLinks(TreeRoot,user,0);
1765 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
1769 void HandleLusers(char** parameters, int pcnt, userrec* user)
1771 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),this->CountServs());
1772 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
1773 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
1774 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
1775 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
1779 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
1781 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
1785 for (int t = 0; t < depth; t++)
1787 matrix[line][t] = ' ';
1789 strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
1791 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1793 ShowMap(Current->GetChild(q),user,depth+2,matrix);
1798 // Ok, prepare to be confused.
1799 // After much mulling over how to approach this, it struck me that
1800 // the 'usual' way of doing a /MAP isnt the best way. Instead of
1801 // keeping track of a ton of ascii characters, and line by line
1802 // under recursion working out where to place them using multiplications
1803 // and divisons, we instead render the map onto a backplane of characters
1804 // (a character matrix), then draw the branches as a series of "L" shapes
1805 // from the nodes. This is not only friendlier on CPU it uses less stack.
1807 void HandleMap(char** parameters, int pcnt, userrec* user)
1809 // This array represents a virtual screen which we will
1810 // "scratch" draw to, as the console device of an irc
1811 // client does not provide for a proper terminal.
1812 char matrix[128][80];
1813 for (unsigned int t = 0; t < 128; t++)
1815 matrix[t][0] = '\0';
1818 // The only recursive bit is called here.
1819 ShowMap(TreeRoot,user,0,matrix);
1820 // Process each line one by one. The algorithm has a limit of
1821 // 128 servers (which is far more than a spanning tree should have
1822 // anyway, so we're ok). This limit can be raised simply by making
1823 // the character matrix deeper, 128 rows taking 10k of memory.
1824 for (int l = 1; l < line; l++)
1826 // scan across the line looking for the start of the
1827 // servername (the recursive part of the algorithm has placed
1828 // the servers at indented positions depending on what they
1830 int first_nonspace = 0;
1831 while (matrix[l][first_nonspace] == ' ')
1836 // Draw the `- (corner) section: this may be overwritten by
1837 // another L shape passing along the same vertical pane, becoming
1838 // a |- (branch) section instead.
1839 matrix[l][first_nonspace] = '-';
1840 matrix[l][first_nonspace-1] = '`';
1842 // Draw upwards until we hit the parent server, causing possibly
1843 // other corners (`-) to become branches (|-)
1844 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
1846 matrix[l2][first_nonspace-1] = '|';
1850 // dump the whole lot to the user. This is the easy bit, honest.
1851 for (int t = 0; t < line; t++)
1853 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
1855 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
1859 int HandleSquit(char** parameters, int pcnt, userrec* user)
1861 TreeServer* s = FindServerMask(parameters[0]);
1864 TreeSocket* sock = s->GetSocket();
1867 WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
1868 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
1873 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
1878 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
1883 void DoPingChecks(time_t curtime)
1885 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
1887 TreeServer* serv = TreeRoot->GetChild(j);
1888 TreeSocket* sock = serv->GetSocket();
1891 if (curtime >= serv->NextPingTime())
1893 if (serv->AnsweredLastPing())
1895 sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
1896 serv->SetNextPingTime(curtime + 60);
1900 // they didnt answer, boot them
1901 WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
1902 sock->Squit(serv,"Ping timeout");
1911 void AutoConnectServers(time_t curtime)
1913 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1915 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
1917 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
1918 x->NextConnectTime = curtime + x->AutoConnect;
1919 TreeServer* CheckDupe = FindServer(x->Name);
1922 // an autoconnected server is not connected. Check if its time to connect it
1923 WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
1924 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1925 Srv->AddSocket(newsocket);
1931 int HandleVersion(char** parameters, int pcnt, userrec* user)
1933 // we've already checked if pcnt > 0, so this is safe
1934 TreeServer* found = FindServerMask(parameters[0]);
1937 std::string Version = found->GetVersion();
1938 WriteServ(user->fd,"351 %s :%s",user->nick,Version.c_str());
1942 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
1947 int HandleConnect(char** parameters, int pcnt, userrec* user)
1949 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1951 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
1953 TreeServer* CheckDupe = FindServer(x->Name);
1956 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);
1957 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1958 Srv->AddSocket(newsocket);
1963 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());
1968 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
1972 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
1974 if (command == "CONNECT")
1976 return this->HandleConnect(parameters,pcnt,user);
1978 else if (command == "SQUIT")
1980 return this->HandleSquit(parameters,pcnt,user);
1982 else if (command == "MAP")
1984 this->HandleMap(parameters,pcnt,user);
1987 else if (command == "LUSERS")
1989 this->HandleLusers(parameters,pcnt,user);
1992 else if (command == "LINKS")
1994 this->HandleLinks(parameters,pcnt,user);
1997 else if ((command == "VERSION") && (pcnt > 0))
1999 this->HandleVersion(parameters,pcnt,user);
2002 else if (Srv->IsValidModuleCommand(command, pcnt, user))
2004 // this bit of code cleverly routes all module commands
2005 // to all remote severs *automatically* so that modules
2006 // can just handle commands locally, without having
2007 // to have any special provision in place for remote
2008 // commands and linking protocols.
2009 std::deque<std::string> params;
2011 for (int j = 0; j < pcnt; j++)
2013 if (strchr(parameters[j],' '))
2015 params.push_back(":" + std::string(parameters[j]));
2019 params.push_back(std::string(parameters[j]));
2022 DoOneToMany(user->nick,command,params);
2027 virtual void OnGetServerDescription(std::string servername,std::string &description)
2029 TreeServer* s = FindServer(servername);
2032 description = s->GetDesc();
2036 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
2038 if (std::string(source->server) == Srv->GetServerName())
2040 std::deque<std::string> params;
2041 params.push_back(dest->nick);
2042 params.push_back(channel->name);
2043 DoOneToMany(source->nick,"INVITE",params);
2047 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
2049 std::deque<std::string> params;
2050 params.push_back(chan->name);
2051 params.push_back(":"+topic);
2052 DoOneToMany(user->nick,"TOPIC",params);
2055 virtual void OnWallops(userrec* user, std::string text)
2057 if (std::string(user->server) == Srv->GetServerName())
2059 std::deque<std::string> params;
2060 params.push_back(":"+text);
2061 DoOneToMany(user->nick,"WALLOPS",params);
2065 virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
2067 if (target_type == TYPE_USER)
2069 userrec* d = (userrec*)dest;
2070 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
2072 std::deque<std::string> params;
2074 params.push_back(d->nick);
2075 params.push_back(":"+text);
2076 DoOneToOne(user->nick,"NOTICE",params,d->server);
2081 if (std::string(user->server) == Srv->GetServerName())
2083 chanrec *c = (chanrec*)dest;
2084 std::deque<TreeServer*> list;
2085 GetListOfServersForChannel(c,list);
2086 unsigned int ucount = list.size();
2087 for (unsigned int i = 0; i < ucount; i++)
2089 TreeSocket* Sock = list[i]->GetSocket();
2091 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+std::string(c->name)+" :"+text);
2097 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
2099 if (target_type == TYPE_USER)
2101 // route private messages which are targetted at clients only to the server
2102 // which needs to receive them
2103 userrec* d = (userrec*)dest;
2104 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
2106 std::deque<std::string> params;
2108 params.push_back(d->nick);
2109 params.push_back(":"+text);
2110 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
2115 if (std::string(user->server) == Srv->GetServerName())
2117 chanrec *c = (chanrec*)dest;
2118 std::deque<TreeServer*> list;
2119 GetListOfServersForChannel(c,list);
2120 unsigned int ucount = list.size();
2121 for (unsigned int i = 0; i < ucount; i++)
2123 TreeSocket* Sock = list[i]->GetSocket();
2125 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+std::string(c->name)+" :"+text);
2131 virtual void OnBackgroundTimer(time_t curtime)
2133 AutoConnectServers(curtime);
2134 DoPingChecks(curtime);
2137 virtual void OnUserJoin(userrec* user, chanrec* channel)
2139 // Only do this for local users
2140 if (std::string(user->server) == Srv->GetServerName())
2142 std::deque<std::string> params;
2144 params.push_back(channel->name);
2147 // if the channel has a key, force the join by emulating the key.
2148 params.push_back(channel->key);
2150 if (channel->GetUserCounter() > 1)
2152 // not the first in the channel
2153 DoOneToMany(user->nick,"JOIN",params);
2157 // first in the channel, set up their permissions
2158 // and the channel TS with FJOIN.
2160 snprintf(ts,24,"%lu",(unsigned long)channel->age);
2162 params.push_back(channel->name);
2163 params.push_back(ts);
2164 params.push_back("@"+std::string(user->nick));
2165 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
2170 virtual void OnChangeHost(userrec* user, std::string newhost)
2172 // only occurs for local clients
2173 std::deque<std::string> params;
2174 params.push_back(newhost);
2175 DoOneToMany(user->nick,"FHOST",params);
2178 virtual void OnChangeName(userrec* user, std::string gecos)
2180 // only occurs for local clients
2181 std::deque<std::string> params;
2182 params.push_back(gecos);
2183 DoOneToMany(user->nick,"FNAME",params);
2186 virtual void OnUserPart(userrec* user, chanrec* channel)
2188 if (std::string(user->server) == Srv->GetServerName())
2190 std::deque<std::string> params;
2191 params.push_back(channel->name);
2192 DoOneToMany(user->nick,"PART",params);
2196 virtual void OnUserConnect(userrec* user)
2198 char agestr[MAXBUF];
2199 if (std::string(user->server) == Srv->GetServerName())
2201 std::deque<std::string> params;
2202 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
2203 params.push_back(agestr);
2204 params.push_back(user->nick);
2205 params.push_back(user->host);
2206 params.push_back(user->dhost);
2207 params.push_back(user->ident);
2208 params.push_back("+"+std::string(user->modes));
2209 params.push_back(user->ip);
2210 params.push_back(":"+std::string(user->fullname));
2211 DoOneToMany(Srv->GetServerName(),"NICK",params);
2215 virtual void OnUserQuit(userrec* user, std::string reason)
2217 if (std::string(user->server) == Srv->GetServerName())
2219 std::deque<std::string> params;
2220 params.push_back(":"+reason);
2221 DoOneToMany(user->nick,"QUIT",params);
2225 virtual void OnUserPostNick(userrec* user, std::string oldnick)
2227 if (std::string(user->server) == Srv->GetServerName())
2229 std::deque<std::string> params;
2230 params.push_back(user->nick);
2231 DoOneToMany(oldnick,"NICK",params);
2235 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
2237 if (std::string(source->server) == Srv->GetServerName())
2239 std::deque<std::string> params;
2240 params.push_back(chan->name);
2241 params.push_back(user->nick);
2242 params.push_back(":"+reason);
2243 DoOneToMany(source->nick,"KICK",params);
2247 virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
2249 std::deque<std::string> params;
2250 params.push_back(dest->nick);
2251 params.push_back(":"+reason);
2252 DoOneToMany(source->nick,"KILL",params);
2255 virtual void OnRehash(std::string parameter)
2257 if (parameter != "")
2259 std::deque<std::string> params;
2260 params.push_back(parameter);
2261 DoOneToMany(Srv->GetServerName(),"REHASH",params);
2263 if (Srv->MatchText(Srv->GetServerName(),parameter))
2265 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
2266 Srv->RehashServer();
2269 ReadConfiguration(false);
2272 // note: the protocol does not allow direct umode +o except
2273 // via NICK with 8 params. sending OPERTYPE infers +o modechange
2275 virtual void OnOper(userrec* user, std::string opertype)
2277 if (std::string(user->server) == Srv->GetServerName())
2279 std::deque<std::string> params;
2280 params.push_back(opertype);
2281 DoOneToMany(user->nick,"OPERTYPE",params);
2285 void OnLine(userrec* source, std::string host, bool adding, char linetype, long duration, std::string reason)
2287 if (std::string(source->server) == Srv->GetServerName())
2291 char sduration[MAXBUF];
2292 snprintf(sduration,MAXBUF,"%ld",duration);
2293 std::deque<std::string> params;
2294 params.push_back(host);
2295 params.push_back(sduration);
2296 params.push_back(":"+reason);
2297 DoOneToMany(source->nick,linetype+"LINE",params);
2301 std::deque<std::string> params;
2302 params.push_back(host);
2303 DoOneToMany(source->nick,linetype+"LINE",params);
2308 virtual void OnAddGLine(long duration, userrec* source, std::string reason, std::string hostmask)
2310 OnLine(source,hostmask,true,'G',duration,reason);
2313 virtual void OnAddZLine(long duration, userrec* source, std::string reason, std::string ipmask)
2315 OnLine(source,ipmask,true,'Z',duration,reason);
2318 virtual void OnAddQLine(long duration, userrec* source, std::string reason, std::string nickmask)
2320 OnLine(source,nickmask,true,'Q',duration,reason);
2323 virtual void OnAddELine(long duration, userrec* source, std::string reason, std::string hostmask)
2325 OnLine(source,hostmask,true,'E',duration,reason);
2328 virtual void OnDelGLine(userrec* source, std::string hostmask)
2330 OnLine(source,hostmask,false,'G',0,"");
2333 virtual void OnDelZLine(userrec* source, std::string ipmask)
2335 OnLine(source,ipmask,false,'Z',0,"");
2338 virtual void OnDelQLine(userrec* source, std::string nickmask)
2340 OnLine(source,nickmask,false,'Q',0,"");
2343 virtual void OnDelELine(userrec* source, std::string hostmask)
2345 OnLine(source,hostmask,false,'E',0,"");
2348 virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
2350 if (std::string(user->server) == Srv->GetServerName())
2352 if (target_type == TYPE_USER)
2354 userrec* u = (userrec*)dest;
2355 std::deque<std::string> params;
2356 params.push_back(u->nick);
2357 params.push_back(text);
2358 DoOneToMany(user->nick,"MODE",params);
2362 chanrec* c = (chanrec*)dest;
2363 std::deque<std::string> params;
2364 params.push_back(c->name);
2365 params.push_back(text);
2366 DoOneToMany(user->nick,"MODE",params);
2371 virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
2373 TreeSocket* s = (TreeSocket*)opaque;
2376 if (target_type == TYPE_USER)
2378 userrec* u = (userrec*)target;
2379 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
2383 chanrec* c = (chanrec*)target;
2384 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
2389 virtual ~ModuleSpanningTree()
2394 virtual Version GetVersion()
2396 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
2401 class ModuleSpanningTreeFactory : public ModuleFactory
2404 ModuleSpanningTreeFactory()
2408 ~ModuleSpanningTreeFactory()
2412 virtual Module * CreateModule()
2414 TreeProtocolModule = new ModuleSpanningTree;
2415 return TreeProtocolModule;
2421 extern "C" void * init_module( void )
2423 return new ModuleSpanningTreeFactory;