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>
36 #include "helperfuncs.h"
38 #include "inspstring.h"
44 #define nspace __gnu_cxx
50 * The server list in InspIRCd is maintained as two structures
51 * which hold the data in different ways. Most of the time, we
52 * want to very quicky obtain three pieces of information:
54 * (1) The information on a server
55 * (2) The information on the server we must send data through
56 * to actually REACH the server we're after
57 * (3) Potentially, the child/parent objects of this server
59 * The InspIRCd spanning protocol provides easy access to these
60 * by storing the data firstly in a recursive structure, where
61 * each item references its parent item, and a dynamic list
62 * of child items, and another structure which stores the items
63 * hashed, linearly. This means that if we want to find a server
64 * by name quickly, we can look it up in the hash, avoiding
65 * any O(n) lookups. If however, during a split or sync, we want
66 * to apply an operation to a server, and any of its child objects
67 * we can resort to recursion to walk the tree structure.
70 class ModuleSpanningTree;
71 static ModuleSpanningTree* TreeProtocolModule;
73 extern std::vector<Module*> modules;
74 extern std::vector<ircd_module*> factory;
77 /* Any socket can have one of five states at any one time.
78 * The LISTENER state indicates a socket which is listening
79 * for connections. It cannot receive data itself, only incoming
81 * The CONNECTING state indicates an outbound socket which is
82 * waiting to be writeable.
83 * The WAIT_AUTH_1 state indicates the socket is outbound and
84 * has successfully connected, but has not yet sent and received
86 * The WAIT_AUTH_2 state indicates that the socket is inbound
87 * (allocated by a LISTENER) but has not yet sent and received
89 * The CONNECTED state represents a fully authorized, fully
92 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
94 /* We need to import these from the core for use in netbursts */
95 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
96 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;
97 extern user_hash clientlist;
98 extern chan_hash chanlist;
100 /* Foward declarations */
104 /* This variable represents the root of the server tree
105 * (for all intents and purposes, it's us)
107 TreeServer *TreeRoot;
109 /* This hash_map holds the hash equivalent of the server
110 * tree, used for rapid linear lookups.
112 typedef nspace::hash_map<std::string, TreeServer*> server_hash;
113 server_hash serverlist;
115 /* More forward declarations */
116 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string target);
117 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string omit);
118 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> ¶ms);
119 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, std::string command, std::deque<std::string> ¶ms);
120 void ReadConfiguration(bool rebind);
122 /* Imported from xline.cpp for use during netburst */
123 extern std::vector<KLine> klines;
124 extern std::vector<GLine> glines;
125 extern std::vector<ZLine> zlines;
126 extern std::vector<QLine> qlines;
127 extern std::vector<ELine> elines;
130 /* Each server in the tree is represented by one class of
131 * type TreeServer. A locally connected TreeServer can
132 * have a class of type TreeSocket associated with it, for
133 * remote servers, the TreeSocket entry will be NULL.
134 * Each server also maintains a pointer to its parent
135 * (NULL if this server is ours, at the top of the tree)
136 * and a pointer to its "Route" (see the comments in the
137 * constructors below), and also a dynamic list of pointers
138 * to its children which can be iterated recursively
139 * if required. Creating or deleting objects of type
140 * TreeServer automatically maintains the hash_map of
141 * TreeServer items, deleting and inserting them as they
142 * are created and destroyed.
147 TreeServer* Parent; /* Parent entry */
148 TreeServer* Route; /* Route entry */
149 std::vector<TreeServer*> Children; /* List of child objects */
150 std::string ServerName; /* Server's name */
151 std::string ServerDesc; /* Server's description */
152 std::string VersionString; /* Version string or empty string */
153 int UserCount; /* Not used in this version */
154 int OperCount; /* Not used in this version */
155 TreeSocket* Socket; /* For directly connected servers this points at the socket object */
156 time_t NextPing; /* After this time, the server should be PINGed*/
157 bool LastPingWasGood; /* True if the server responded to the last PING with a PONG */
161 /* We don't use this constructor. Its a dummy, and won't cause any insertion
162 * of the TreeServer into the hash_map. See below for the two we DO use.
170 UserCount = OperCount = 0;
171 VersionString = GetVersionString();
174 /* We use this constructor only to create the 'root' item, TreeRoot, which
175 * represents our own server. Therefore, it has no route, no parent, and
176 * no socket associated with it. Its version string is our own local version.
178 TreeServer(std::string Name, std::string Desc) : ServerName(Name), ServerDesc(Desc)
182 UserCount = OperCount = 0;
183 VersionString = GetVersionString();
188 /* When we create a new server, we call this constructor to initialize it.
189 * This constructor initializes the server's Route and Parent, and sets up
190 * its ping counters so that it will be pinged one minute from now.
192 TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name), ServerDesc(Desc), Socket(Sock)
195 UserCount = OperCount = 0;
196 this->SetNextPingTime(time(NULL) + 60);
199 /* find the 'route' for this server (e.g. the one directly connected
200 * to the local server, which we can use to reach it)
202 * In the following example, consider we have just added a TreeServer
203 * class for server G on our network, of which we are server A.
204 * To route traffic to G (marked with a *) we must send the data to
205 * B (marked with a +) so this algorithm initializes the 'Route'
206 * value to point at whichever server traffic must be routed through
207 * to get here. If we were to try this algorithm with server B,
208 * the Route pointer would point at its own object ('this').
218 * We only run this algorithm when a server is created, as
219 * the routes remain constant while ever the server exists, and
220 * do not need to be re-calculated.
224 if (Route == TreeRoot)
230 while (this->Route->GetParent() != TreeRoot)
232 this->Route = Route->GetParent();
236 /* Because recursive code is slow and takes a lot of resources,
237 * we store two representations of the server tree. The first
238 * is a recursive structure where each server references its
239 * children and its parent, which is used for netbursts and
240 * netsplits to dump the whole dataset to the other server,
241 * and the second is used for very fast lookups when routing
242 * messages and is instead a hash_map, where each item can
243 * be referenced by its server name. The AddHashEntry()
244 * call below automatically inserts each TreeServer class
245 * into the hash_map as it is created. There is a similar
246 * maintainance call in the destructor to tidy up deleted
250 this->AddHashEntry();
253 /* This method is used to add the structure to the
254 * hash_map for linear searches. It is only called
255 * by the constructors.
259 server_hash::iterator iter;
260 iter = serverlist.find(this->ServerName);
261 if (iter == serverlist.end())
262 serverlist[this->ServerName] = this;
265 /* This method removes the reference to this object
266 * from the hash_map which is used for linear searches.
267 * It is only called by the default destructor.
271 server_hash::iterator iter;
272 iter = serverlist.find(this->ServerName);
273 if (iter != serverlist.end())
274 serverlist.erase(iter);
277 /* These accessors etc should be pretty self-
281 TreeServer* GetRoute()
286 std::string GetName()
288 return this->ServerName;
291 std::string GetDesc()
293 return this->ServerDesc;
296 std::string GetVersion()
298 return this->VersionString;
301 void SetNextPingTime(time_t t)
304 LastPingWasGood = false;
307 time_t NextPingTime()
309 return this->NextPing;
312 bool AnsweredLastPing()
314 return LastPingWasGood;
319 LastPingWasGood = true;
324 return this->UserCount;
329 return this->OperCount;
332 TreeSocket* GetSocket()
337 TreeServer* GetParent()
342 void SetVersion(std::string Version)
344 VersionString = Version;
347 unsigned int ChildCount()
349 return Children.size();
352 TreeServer* GetChild(unsigned int n)
354 if (n < Children.size())
356 /* Make sure they cant request
357 * an out-of-range object. After
358 * all we know what these programmer
359 * types are like *grin*.
369 void AddChild(TreeServer* Child)
371 Children.push_back(Child);
374 bool DelChild(TreeServer* Child)
376 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
387 /* Removes child nodes of this node, and of that node, etc etc.
388 * This is used during netsplits to automatically tidy up the
389 * server tree. It is slow, we don't use it for much else.
393 bool stillchildren = true;
394 while (stillchildren)
396 stillchildren = false;
397 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
399 TreeServer* s = (TreeServer*)*a;
403 stillchildren = true;
412 /* We'd better tidy up after ourselves, eh? */
413 this->DelHashEntry();
417 /* The Link class might as well be a struct,
418 * but this is C++ and we don't believe in structs (!).
419 * It holds the entire information of one <link>
420 * tag from the main config file. We maintain a list
421 * of them, and populate the list on rehash/load.
430 std::string SendPass;
431 std::string RecvPass;
432 unsigned long AutoConnect;
433 time_t NextConnectTime;
436 /* The usual stuff for inspircd modules,
437 * plus the vector of Link classes which we
438 * use to store the <link> tags from the config
443 std::vector<Link> LinkBlocks;
445 /* Yay for fast searches!
446 * This is hundreds of times faster than recursion
447 * or even scanning a linked list, especially when
448 * there are more than a few servers to deal with.
451 TreeServer* FindServer(std::string ServerName)
453 server_hash::iterator iter;
454 iter = serverlist.find(ServerName);
455 if (iter != serverlist.end())
465 /* Returns the locally connected server we must route a
466 * message through to reach server 'ServerName'. This
467 * only applies to one-to-one and not one-to-many routing.
468 * See the comments for the constructor of TreeServer
471 TreeServer* BestRouteTo(std::string ServerName)
473 if (ServerName.c_str() == TreeRoot->GetName())
475 TreeServer* Found = FindServer(ServerName);
478 return Found->GetRoute();
486 /* Find the first server matching a given glob mask.
487 * Theres no find-using-glob method of hash_map [awwww :-(]
488 * so instead, we iterate over the list using an iterator
489 * and match each one until we get a hit. Yes its slow,
492 TreeServer* FindServerMask(std::string ServerName)
494 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
496 if (Srv->MatchText(i->first,ServerName))
502 /* A convenient wrapper that returns true if a server exists */
503 bool IsServer(std::string ServerName)
505 return (FindServer(ServerName) != NULL);
508 /* Every SERVER connection inbound or outbound is represented by
509 * an object of type TreeSocket.
510 * TreeSockets, being inherited from InspSocket, can be tied into
511 * the core socket engine, and we cn therefore receive activity events
512 * for them, just like activex objects on speed. (yes really, that
513 * is a technical term!) Each of these which relates to a locally
514 * connected server is assocated with it, by hooking it onto a
515 * TreeSocket class using its constructor. In this way, we can
516 * maintain a list of servers, some of which are directly connected,
517 * some of which are not.
520 class TreeSocket : public InspSocket
523 std::string in_buffer;
524 ServerState LinkState;
525 std::string InboundServerName;
526 std::string InboundDescription;
528 int num_lost_servers;
530 bool LastPingWasGood;
535 /* Because most of the I/O gubbins are encapsulated within
536 * InspSocket, we just call the superclass constructor for
537 * most of the action, and append a few of our own values
540 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
541 : InspSocket(host, port, listening, maxtime)
544 this->LinkState = LISTENER;
547 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
548 : InspSocket(host, port, listening, maxtime)
551 this->LinkState = CONNECTING;
554 /* When a listening socket gives us a new file descriptor,
555 * we must associate it with a socket without creating a new
556 * connection. This constructor is used for this purpose.
558 TreeSocket(int newfd, char* ip)
559 : InspSocket(newfd, ip)
561 this->LinkState = WAIT_AUTH_1;
564 /* When an outbound connection finishes connecting, we receive
565 * this event, and must send our SERVER string to the other
566 * side. If the other side is happy, as outlined in the server
567 * to server docs on the inspircd.org site, the other side
568 * will then send back its own server string.
570 virtual bool OnConnected()
572 if (this->LinkState == CONNECTING)
574 Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
575 /* we do not need to change state here. */
576 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
578 if (x->Name == this->myhost)
580 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
581 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
586 /* There is a (remote) chance that between the /CONNECT and the connection
587 * being accepted, some muppet has removed the <link> block and rehashed.
588 * If that happens the connection hangs here until it's closed. Unlikely
589 * and rather harmless.
594 virtual void OnError(InspSocketError e)
596 /* We don't handle this method, because all our
597 * dirty work is done in OnClose() (see below)
598 * which is still called on error conditions too.
602 virtual int OnDisconnect()
604 /* For the same reason as above, we don't
605 * handle OnDisconnect()
610 /* Recursively send the server tree with distances as hops.
611 * This is used during network burst to inform the other server
612 * (and any of ITS servers too) of what servers we know about.
613 * If at any point any of these servers already exist on the other
614 * end, our connection may be terminated. The hopcounts given
615 * by this function are relative, this doesn't matter so long as
616 * they are all >1, as all the remote servers re-calculate them
617 * to be relative too, with themselves as hop 0.
619 void SendServers(TreeServer* Current, TreeServer* s, int hops)
622 for (unsigned int q = 0; q < Current->ChildCount(); q++)
624 TreeServer* recursive_server = Current->GetChild(q);
625 if (recursive_server != s)
627 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
628 this->WriteLine(command);
629 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
630 /* down to next level */
631 this->SendServers(recursive_server, s, hops+1);
636 /* This function forces this server to quit, removing this server
637 * and any users on it (and servers and users below that, etc etc).
638 * It's very slow and pretty clunky, but luckily unless your network
639 * is having a REAL bad hair day, this function shouldnt be called
640 * too many times a month ;-)
642 void SquitServer(TreeServer* Current)
644 /* recursively squit the servers attached to 'Current'.
645 * We're going backwards so we don't remove users
646 * while we still need them ;)
648 for (unsigned int q = 0; q < Current->ChildCount(); q++)
650 TreeServer* recursive_server = Current->GetChild(q);
651 this->SquitServer(recursive_server);
653 /* Now we've whacked the kids, whack self */
655 bool quittingpeople = true;
656 while (quittingpeople)
658 /* Yup i know, "ew". We cant continue to loop through the
659 * iterator if we modify it, so whenever we modify it with a
660 * QUIT we have to start alllll over again. If anyone knows
661 * a better faster way of *safely* doing this, please let me
664 quittingpeople = false;
665 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
667 if (!strcasecmp(u->second->server,Current->GetName().c_str()))
669 Srv->QuitUser(u->second,Current->GetName()+" "+std::string(Srv->GetServerName()));
671 quittingpeople = true;
678 /* This is a wrapper function for SquitServer above, which
679 * does some validation first and passes on the SQUIT to all
680 * other remaining servers.
682 void Squit(TreeServer* Current,std::string reason)
686 std::deque<std::string> params;
687 params.push_back(Current->GetName());
688 params.push_back(":"+reason);
689 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
690 if (Current->GetParent() == TreeRoot)
692 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
696 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
698 num_lost_servers = 0;
700 SquitServer(Current);
702 Current->GetParent()->DelChild(Current);
704 WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
708 log(DEFAULT,"Squit from unknown server");
713 bool ForceMode(std::string source, std::deque<std::string> params)
715 userrec* who = new userrec;
716 who->fd = FD_MAGIC_NUMBER;
717 if (params.size() < 2)
720 for (unsigned int q = 0; q < params.size(); q++)
722 modelist[q] = (char*)params[q].c_str();
724 Srv->SendMode(modelist,params.size(),who);
725 DoOneToAllButSender(source,"FMODE",params,source);
731 bool ForceTopic(std::string source, std::deque<std::string> params)
733 if (params.size() != 4)
735 std::string channel = params[0];
736 time_t ts = atoi(params[1].c_str());
737 std::string setby = params[2];
738 std::string topic = params[3];
740 chanrec* c = Srv->FindChannel(channel);
743 if ((ts >= c->topicset) || (!*c->topic))
745 std::string oldtopic = c->topic;
746 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
747 strlcpy(c->setby,setby.c_str(),NICKMAX);
749 /* if the topic text is the same as the current topic,
750 * dont bother to send the TOPIC command out, just silently
751 * update the set time and set nick.
753 if (oldtopic != topic)
754 WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
759 /* all done, send it on its way */
760 params[3] = ":" + params[3];
761 DoOneToAllButSender(source,"FTOPIC",params,source);
766 /* FJOIN, similar to unreal SJOIN */
767 bool ForceJoin(std::string source, std::deque<std::string> params)
769 if (params.size() < 3)
773 char modestring[MAXBUF];
774 char* mode_users[127];
775 mode_users[0] = first;
776 mode_users[1] = modestring;
777 strcpy(mode_users[1],"+");
778 unsigned int modectr = 2;
781 std::string channel = params[0];
782 time_t TS = atoi(params[1].c_str());
785 chanrec* chan = Srv->FindChannel(channel);
790 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
792 /* default is a high value, which if we dont have this
793 * channel will let the other side apply their modes.
795 time_t ourTS = time(NULL)+600;
796 chanrec* us = Srv->FindChannel(channel);
802 log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
804 /* do this first, so our mode reversals are correctly received by other servers
805 * if there is a TS collision.
807 DoOneToAllButSender(source,"FJOIN",params,source);
809 for (unsigned int usernum = 2; usernum < params.size(); usernum++)
811 /* process one channel at a time, applying modes. */
812 char* usr = (char*)params[usernum].c_str();
813 char permissions = *usr;
818 mode_users[modectr++] = usr;
819 strlcat(modestring,"o",MAXBUF);
823 mode_users[modectr++] = usr;
824 strlcat(modestring,"h",MAXBUF);
828 mode_users[modectr++] = usr;
829 strlcat(modestring,"v",MAXBUF);
832 who = Srv->FindNick(usr);
835 Srv->JoinUserToChannel(who,channel,key);
836 if (modectr >= (MAXMODES-1))
838 /* theres a mode for this user. push them onto the mode queue, and flush it
839 * if there are more than MAXMODES to go.
841 if ((ourTS >= TS) || (Srv->IsUlined(who->server)))
843 /* We also always let u-lined clients win, no matter what the TS value */
844 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
845 Srv->SendMode(mode_users,modectr,who);
849 log(DEBUG,"Their channel newer than ours, bouncing their modes");
851 std::deque<std::string> params;
852 /* modes are now being UNSET... */
853 *mode_users[1] = '-';
854 for (unsigned int x = 0; x < modectr; x++)
856 params.push_back(mode_users[x]);
858 // tell everyone to bounce the modes. bad modes, bad!
859 DoOneToMany(Srv->GetServerName(),"FMODE",params);
861 strcpy(mode_users[1],"+");
866 /* there werent enough modes built up to flush it during FJOIN,
867 * or, there are a number left over. flush them out.
869 if ((modectr > 2) && (who))
873 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
874 Srv->SendMode(mode_users,modectr,who);
878 log(DEBUG,"Their channel newer than ours, bouncing their modes");
879 std::deque<std::string> params;
880 *mode_users[1] = '-';
881 for (unsigned int x = 0; x < modectr; x++)
883 params.push_back(mode_users[x]);
885 DoOneToMany(Srv->GetServerName(),"FMODE",params);
892 bool IntroduceClient(std::string source, std::deque<std::string> params)
894 if (params.size() < 8)
896 // NICK age nick host dhost ident +modes ip :gecos
898 std::string nick = params[1];
899 std::string host = params[2];
900 std::string dhost = params[3];
901 std::string ident = params[4];
902 time_t age = atoi(params[0].c_str());
903 std::string modes = params[5];
904 while (*(modes.c_str()) == '+')
906 char* m = (char*)modes.c_str();
910 std::string ip = params[6];
911 std::string gecos = params[7];
912 char* tempnick = (char*)nick.c_str();
913 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
915 user_hash::iterator iter;
916 iter = clientlist.find(tempnick);
917 if (iter != clientlist.end())
920 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);
921 this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
925 clientlist[tempnick] = new userrec();
926 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
927 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
928 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
929 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
930 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
931 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
932 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
933 clientlist[tempnick]->registered = 7;
934 clientlist[tempnick]->signon = age;
935 strlcpy(clientlist[tempnick]->modes, modes.c_str(),53);
936 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
937 for (int i = 0; i < MAXCHANS; i++)
939 clientlist[tempnick]->chans[i].channel = NULL;
940 clientlist[tempnick]->chans[i].uc_modes = 0;
944 WriteOpers("*** Client connecting at %s: %s!%s@%s [%s]",clientlist[tempnick]->server,clientlist[tempnick]->nick,clientlist[tempnick]->ident,clientlist[tempnick]->host,clientlist[tempnick]->ip);
946 params[7] = ":" + params[7];
947 DoOneToAllButSender(source,"NICK",params,source);
951 /* Send one or more FJOINs for a channel of users.
952 * If the length of a single line is more than 480-NICKMAX
953 * in length, it is split over multiple lines.
955 void SendFJoins(TreeServer* Current, chanrec* c)
958 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
959 std::vector<char*> *ulist = c->GetUsers();
960 for (unsigned int i = 0; i < ulist->size(); i++)
962 char* o = (*ulist)[i];
963 userrec* otheruser = (userrec*)o;
964 strlcat(list," ",MAXBUF);
965 strlcat(list,cmode(otheruser,c),MAXBUF);
966 strlcat(list,otheruser->nick,MAXBUF);
967 if (strlen(list)>(480-NICKMAX))
969 this->WriteLine(list);
970 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
973 if (list[strlen(list)-1] != ':')
975 this->WriteLine(list);
979 /* Send G, Q, Z and E lines */
980 void SendXLines(TreeServer* Current)
983 /* Yes, these arent too nice looking, but they get the job done */
984 for (std::vector<ZLine>::iterator i = zlines.begin(); i != zlines.end(); i++)
986 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);
987 this->WriteLine(data);
989 for (std::vector<QLine>::iterator i = qlines.begin(); i != qlines.end(); i++)
991 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);
992 this->WriteLine(data);
994 for (std::vector<GLine>::iterator i = glines.begin(); i != glines.end(); i++)
996 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);
997 this->WriteLine(data);
999 for (std::vector<ELine>::iterator i = elines.begin(); i != elines.end(); i++)
1001 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);
1002 this->WriteLine(data);
1006 /* Send channel modes and topics */
1007 void SendChannelModes(TreeServer* Current)
1010 std::deque<std::string> list;
1011 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
1013 SendFJoins(Current, c->second);
1014 snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
1015 this->WriteLine(data);
1016 if (*c->second->topic)
1018 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);
1019 this->WriteLine(data);
1021 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
1023 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
1024 this->WriteLine(data);
1026 FOREACH_MOD OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this);
1028 c->second->GetExtList(list);
1029 for (unsigned int j = 0; j < list.size(); j++)
1031 FOREACH_MOD OnSyncChannelMetaData(c->second,(Module*)TreeProtocolModule,(void*)this,list[j]);
1036 /* send all users and their oper state/modes */
1037 void SendUsers(TreeServer* Current)
1040 std::deque<std::string> list;
1041 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
1043 if (u->second->registered == 7)
1045 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);
1046 this->WriteLine(data);
1047 if (strchr(u->second->modes,'o'))
1049 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
1051 FOREACH_MOD OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this);
1053 u->second->GetExtList(list);
1054 for (unsigned int j = 0; j < list.size(); j++)
1056 FOREACH_MOD OnSyncUserMetaData(u->second,(Module*)TreeProtocolModule,(void*)this,list[j]);
1062 /* This function is called when we want to send a netburst to a local
1063 * server. There is a set order we must do this, because for example
1064 * users require their servers to exist, and channels require their
1065 * users to exist. You get the idea.
1067 void DoBurst(TreeServer* s)
1069 Srv->SendOpers("*** Bursting to \2"+s->GetName()+"\2.");
1070 this->WriteLine("BURST");
1071 /* send our version string */
1072 this->WriteLine(":"+Srv->GetServerName()+" VERSION :"+GetVersionString());
1073 /* Send server tree */
1074 this->SendServers(TreeRoot,s,1);
1075 /* Send users and their oper status */
1077 /* Send everything else (channel modes, xlines etc) */
1078 this->SendChannelModes(s);
1079 this->SendXLines(s);
1080 this->WriteLine("ENDBURST");
1081 Srv->SendOpers("*** Finished bursting to \2"+s->GetName()+"\2.");
1084 /* This function is called when we receive data from a remote
1085 * server. We buffer the data in a std::string (it doesnt stay
1086 * there for long), reading using InspSocket::Read() which can
1087 * read up to 16 kilobytes in one operation.
1089 * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
1090 * THE SOCKET OBJECT FOR US.
1092 virtual bool OnDataReady()
1094 char* data = this->Read();
1097 this->in_buffer += data;
1098 /* While there is at least one new line in the buffer,
1099 * do something useful (we hope!) with it.
1101 while (in_buffer.find("\n") != std::string::npos)
1103 char* line = (char*)in_buffer.c_str();
1104 std::string ret = "";
1105 while ((*line != '\n') && (strlen(line)))
1110 if ((*line == '\n') || (*line == '\r'))
1113 /* Process this one, abort if it
1114 * didnt return true.
1116 if (!this->ProcessLine(ret))
1122 return (data != NULL);
1125 int WriteLine(std::string line)
1127 return this->Write(line + "\r\n");
1130 /* Handle ERROR command */
1131 bool Error(std::deque<std::string> params)
1133 if (params.size() < 1)
1135 std::string Errmsg = params[0];
1136 std::string SName = myhost;
1137 if (InboundServerName != "")
1139 SName = InboundServerName;
1141 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
1142 /* we will return false to cause the socket to close.
1147 /* Because the core won't let users or even SERVERS set +o,
1148 * we use the OPERTYPE command to do this.
1150 bool OperType(std::string prefix, std::deque<std::string> ¶ms)
1152 if (params.size() != 1)
1154 std::string opertype = params[0];
1155 userrec* u = Srv->FindNick(prefix);
1158 strlcpy(u->oper,opertype.c_str(),NICKMAX);
1159 if (!strchr(u->modes,'o'))
1161 strcat(u->modes,"o");
1163 DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
1168 /* Because Andy insists that services-compatible servers must
1169 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
1171 bool ForceNick(std::string prefix, std::deque<std::string> ¶ms)
1173 if (params.size() < 3)
1175 userrec* u = Srv->FindNick(params[0]);
1178 Srv->ChangeUserNick(u,params[1]);
1179 u->age = atoi(params[2].c_str());
1180 DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
1185 bool ServiceJoin(std::string prefix, std::deque<std::string> ¶ms)
1187 if (params.size() < 2)
1189 userrec* u = Srv->FindNick(params[0]);
1192 Srv->JoinUserToChannel(u,params[1],"");
1193 DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
1198 bool RemoteRehash(std::string prefix, std::deque<std::string> ¶ms)
1200 if (params.size() < 1)
1202 std::string servermask = params[0];
1203 if (Srv->MatchText(Srv->GetServerName(),servermask))
1205 Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
1206 Srv->RehashServer();
1207 ReadConfiguration(false);
1209 DoOneToAllButSender(prefix,"REHASH",params,prefix);
1213 bool RemoteKill(std::string prefix, std::deque<std::string> ¶ms)
1215 if (params.size() != 2)
1217 std::string nick = params[0];
1218 userrec* u = Srv->FindNick(prefix);
1219 userrec* who = Srv->FindNick(nick);
1222 /* Prepend kill source, if we don't have one */
1223 std::string sourceserv = prefix;
1226 sourceserv = u->server;
1228 if (*(params[1].c_str()) != '[')
1230 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
1232 std::string reason = params[1];
1233 params[1] = ":" + params[1];
1234 DoOneToAllButSender(prefix,"KILL",params,sourceserv);
1235 Srv->QuitUser(who,reason);
1240 bool LocalPong(std::string prefix, std::deque<std::string> ¶ms)
1242 if (params.size() < 1)
1244 TreeServer* ServerSource = FindServer(prefix);
1247 ServerSource->SetPingFlag();
1252 bool MetaData(std::string prefix, std::deque<std::string> ¶ms)
1254 if (params.size() < 3)
1256 TreeServer* ServerSource = FindServer(prefix);
1259 if (*(params[0].c_str()) == '#')
1261 chanrec* c = Srv->FindChannel(params[0]);
1264 FOREACH_MOD OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]);
1269 userrec* u = Srv->FindNick(params[0]);
1272 FOREACH_MOD OnDecodeMetaData(TYPE_USER,u,params[1],params[2]);
1276 params[2] = ":" + params[2];
1277 DoOneToAllButSender(prefix,"METADATA",params,prefix);
1281 bool ServerVersion(std::string prefix, std::deque<std::string> ¶ms)
1283 if (params.size() < 1)
1285 TreeServer* ServerSource = FindServer(prefix);
1288 ServerSource->SetVersion(params[0]);
1290 params[0] = ":" + params[0];
1291 DoOneToAllButSender(prefix,"VERSION",params,prefix);
1295 bool ChangeHost(std::string prefix, std::deque<std::string> ¶ms)
1297 if (params.size() < 1)
1299 userrec* u = Srv->FindNick(prefix);
1302 Srv->ChangeHost(u,params[0]);
1303 DoOneToAllButSender(prefix,"FHOST",params,u->server);
1308 bool AddLine(std::string prefix, std::deque<std::string> ¶ms)
1310 if (params.size() < 6)
1312 std::string linetype = params[0]; /* Z, Q, E, G, K */
1313 std::string mask = params[1]; /* Line type dependent */
1314 std::string source = params[2]; /* may not be online or may be a server */
1315 std::string settime = params[3]; /* EPOCH time set */
1316 std::string duration = params[4]; /* Duration secs */
1317 std::string reason = params[5];
1319 switch (*(linetype.c_str()))
1322 add_zline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1323 zline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1326 add_qline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1327 qline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1330 add_eline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1331 eline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1334 add_gline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1335 gline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1338 add_kline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1341 /* Just in case... */
1342 Srv->SendOpers("*** \2WARNING\2: Invalid xline type '"+linetype+"' sent by server "+prefix+", ignored!");
1345 /* Send it on its way */
1346 params[5] = ":" + params[5];
1347 DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
1351 bool ChangeName(std::string prefix, std::deque<std::string> ¶ms)
1353 if (params.size() < 1)
1355 userrec* u = Srv->FindNick(prefix);
1358 Srv->ChangeGECOS(u,params[0]);
1359 params[0] = ":" + params[0];
1360 DoOneToAllButSender(prefix,"FNAME",params,u->server);
1365 bool Whois(std::string prefix, std::deque<std::string> ¶ms)
1367 if (params.size() < 1)
1369 userrec* u = Srv->FindNick(prefix);
1372 // an incoming request
1373 if (params.size() == 1)
1375 if (std::string(u->server) == Srv->GetServerName())
1377 char signon[MAXBUF];
1379 snprintf(signon,MAXBUF,"%lu",(unsigned long)u->signon);
1380 snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((u->idle_lastmsg)-time(NULL)));
1381 std::deque<std::string> par;
1382 par.push_back(u->nick);
1383 par.push_back(signon);
1384 par.push_back(idle);
1385 DoOneToMany(params[0],"IDLE",par);
1389 DoOneToAllButSender(prefix,"IDLE",params,u->server);
1392 else if (params.size() == 3)
1394 if (std::string(u->server) == Srv->GetServerName())
1396 // an incoming reply to a whois we sent out
1397 std::string nick_whoised = prefix;
1398 std::string who_did_the_whois = params[0];
1399 unsigned long signon = atoi(params[1].c_str());
1400 unsigned long idle = atoi(params[2].c_str());
1401 userrec* who_to_send_to = Srv->FindNick(who_did_the_whois);
1403 do_whois(who_to_send_to,u,signon,idle,(char*)nick_whoised.c_str());
1407 DoOneToAllButSender(prefix,"IDLE",params,u->server);
1414 bool LocalPing(std::string prefix, std::deque<std::string> ¶ms)
1416 if (params.size() < 1)
1418 std::string stufftobounce = params[0];
1419 this->WriteLine(":"+Srv->GetServerName()+" PONG "+stufftobounce);
1423 bool RemoteServer(std::string prefix, std::deque<std::string> ¶ms)
1425 if (params.size() < 4)
1427 std::string servername = params[0];
1428 std::string password = params[1];
1429 // hopcount is not used for a remote server, we calculate this ourselves
1430 std::string description = params[3];
1431 TreeServer* ParentOfThis = FindServer(prefix);
1434 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
1437 TreeServer* CheckDupe = FindServer(servername);
1440 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1443 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
1444 ParentOfThis->AddChild(Node);
1445 params[3] = ":" + params[3];
1446 DoOneToAllButSender(prefix,"SERVER",params,prefix);
1447 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
1451 bool Outbound_Reply_Server(std::deque<std::string> ¶ms)
1453 if (params.size() < 4)
1455 std::string servername = params[0];
1456 std::string password = params[1];
1457 int hops = atoi(params[2].c_str());
1460 this->WriteLine("ERROR :Server too far away for authentication");
1463 std::string description = params[3];
1464 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1466 if ((x->Name == servername) && (x->RecvPass == password))
1468 TreeServer* CheckDupe = FindServer(servername);
1471 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1474 // Begin the sync here. this kickstarts the
1475 // other side, waiting in WAIT_AUTH_2 state,
1476 // into starting their burst, as it shows
1477 // that we're happy.
1478 this->LinkState = CONNECTED;
1479 // we should add the details of this server now
1480 // to the servers tree, as a child of the root
1482 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
1483 TreeRoot->AddChild(Node);
1484 params[3] = ":" + params[3];
1485 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
1486 this->bursting = true;
1487 this->DoBurst(Node);
1491 this->WriteLine("ERROR :Invalid credentials");
1495 bool Inbound_Server(std::deque<std::string> ¶ms)
1497 if (params.size() < 4)
1499 std::string servername = params[0];
1500 std::string password = params[1];
1501 int hops = atoi(params[2].c_str());
1504 this->WriteLine("ERROR :Server too far away for authentication");
1507 std::string description = params[3];
1508 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1510 if ((x->Name == servername) && (x->RecvPass == password))
1512 TreeServer* CheckDupe = FindServer(servername);
1515 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1518 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
1519 this->InboundServerName = servername;
1520 this->InboundDescription = description;
1521 // this is good. Send our details: Our server name and description and hopcount of 0,
1522 // along with the sendpass from this block.
1523 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
1524 // move to the next state, we are now waiting for THEM.
1525 this->LinkState = WAIT_AUTH_2;
1529 this->WriteLine("ERROR :Invalid credentials");
1533 void Split(std::string line, bool stripcolon, std::deque<std::string> &n)
1535 if (!strchr(line.c_str(),' '))
1540 std::stringstream s(line);
1541 std::string param = "";
1560 if ((param == ":") && (item > 0))
1583 bool ProcessLine(std::string line)
1585 char* l = (char*)line.c_str();
1586 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
1587 l[strlen(l)-1] = '\0';
1591 Srv->Log(DEBUG,"IN: '"+line+"'");
1592 std::deque<std::string> params;
1593 this->Split(line,true,params);
1594 std::string command = "";
1595 std::string prefix = "";
1596 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
1599 command = params[1];
1600 char* pref = (char*)prefix.c_str();
1608 command = params[0];
1612 switch (this->LinkState)
1617 // Waiting for SERVER command from remote server. Server initiating
1618 // the connection sends the first SERVER command, listening server
1619 // replies with theirs if its happy, then if the initiator is happy,
1620 // it starts to send its net sync, which starts the merge, otherwise
1621 // it sends an ERROR.
1622 if (command == "SERVER")
1624 return this->Inbound_Server(params);
1626 else if (command == "ERROR")
1628 return this->Error(params);
1632 // Waiting for start of other side's netmerge to say they liked our
1634 if (command == "SERVER")
1636 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1640 else if (command == "BURST")
1642 this->LinkState = CONNECTED;
1643 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
1644 TreeRoot->AddChild(Node);
1646 params.push_back(InboundServerName);
1647 params.push_back("*");
1648 params.push_back("1");
1649 params.push_back(":"+InboundDescription);
1650 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
1651 this->bursting = true;
1652 this->DoBurst(Node);
1654 else if (command == "ERROR")
1656 return this->Error(params);
1661 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
1665 if (command == "SERVER")
1667 // another server we connected to, which was in WAIT_AUTH_1 state,
1668 // has just sent us their credentials. If we get this far, theyre
1669 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1670 // if we're happy with this, we should send our netburst which
1671 // kickstarts the merge.
1672 return this->Outbound_Reply_Server(params);
1674 else if (command == "ERROR")
1676 return this->Error(params);
1680 // This is the 'authenticated' state, when all passwords
1681 // have been exchanged and anything past this point is taken
1686 std::string direction = prefix;
1687 userrec* t = Srv->FindNick(prefix);
1690 direction = t->server;
1692 TreeServer* route_back_again = BestRouteTo(direction);
1693 if ((!route_back_again) || (route_back_again->GetSocket() != this))
1695 WriteOpers("*** \2WARNING\2! Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
1700 if (command == "SVSMODE")
1702 /* Services expects us to implement
1703 * SVSMODE. In inspircd its the same as
1708 std::string target = "";
1709 /* Yes, know, this is a mess. Its reasonably fast though as we're
1710 * working with std::string here.
1712 if ((command == "NICK") && (params.size() > 1))
1714 return this->IntroduceClient(prefix,params);
1716 else if (command == "FJOIN")
1718 return this->ForceJoin(prefix,params);
1720 else if (command == "SERVER")
1722 return this->RemoteServer(prefix,params);
1724 else if (command == "ERROR")
1726 return this->Error(params);
1728 else if (command == "OPERTYPE")
1730 return this->OperType(prefix,params);
1732 else if (command == "FMODE")
1734 return this->ForceMode(prefix,params);
1736 else if (command == "KILL")
1738 return this->RemoteKill(prefix,params);
1740 else if (command == "FTOPIC")
1742 return this->ForceTopic(prefix,params);
1744 else if (command == "REHASH")
1746 return this->RemoteRehash(prefix,params);
1748 else if (command == "METADATA")
1750 return this->MetaData(prefix,params);
1752 else if (command == "PING")
1754 return this->LocalPing(prefix,params);
1756 else if (command == "PONG")
1758 return this->LocalPong(prefix,params);
1760 else if (command == "VERSION")
1762 return this->ServerVersion(prefix,params);
1764 else if (command == "FHOST")
1766 return this->ChangeHost(prefix,params);
1768 else if (command == "FNAME")
1770 return this->ChangeName(prefix,params);
1772 else if (command == "ADDLINE")
1774 return this->AddLine(prefix,params);
1776 else if (command == "SVSNICK")
1780 prefix = this->GetName();
1782 return this->ForceNick(prefix,params);
1784 else if (command == "IDLE")
1786 return this->Whois(prefix,params);
1788 else if (command == "SVSJOIN")
1792 prefix = this->GetName();
1794 return this->ServiceJoin(prefix,params);
1796 else if (command == "SQUIT")
1798 if (params.size() == 2)
1800 this->Squit(FindServer(params[0]),params[1]);
1804 else if (command == "ENDBURST")
1806 this->bursting = false;
1811 // not a special inter-server command.
1812 // Emulate the actual user doing the command,
1813 // this saves us having a huge ugly parser.
1814 userrec* who = Srv->FindNick(prefix);
1815 std::string sourceserv = this->myhost;
1816 if (this->InboundServerName != "")
1818 sourceserv = this->InboundServerName;
1823 target = who->server;
1824 char* strparams[127];
1825 for (unsigned int q = 0; q < params.size(); q++)
1827 strparams[q] = (char*)params[q].c_str();
1829 Srv->CallCommandHandler(command, strparams, params.size(), who);
1833 // its not a user. Its either a server, or somethings screwed up.
1834 if (IsServer(prefix))
1836 target = Srv->GetServerName();
1840 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
1844 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1853 virtual std::string GetName()
1855 std::string sourceserv = this->myhost;
1856 if (this->InboundServerName != "")
1858 sourceserv = this->InboundServerName;
1863 virtual void OnTimeout()
1865 if (this->LinkState == CONNECTING)
1867 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
1871 virtual void OnClose()
1873 // Connection closed.
1874 // If the connection is fully up (state CONNECTED)
1875 // then propogate a netsplit to all peers.
1876 std::string quitserver = this->myhost;
1877 if (this->InboundServerName != "")
1879 quitserver = this->InboundServerName;
1881 TreeServer* s = FindServer(quitserver);
1884 Squit(s,"Remote host closed the connection");
1888 virtual int OnIncomingConnection(int newsock, char* ip)
1890 TreeSocket* s = new TreeSocket(newsock, ip);
1896 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
1898 for (unsigned int c = 0; c < list.size(); c++)
1900 if (list[c] == server)
1905 list.push_back(server);
1908 // returns a list of DIRECT servernames for a specific channel
1909 void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
1911 std::vector<char*> *ulist = c->GetUsers();
1912 unsigned int ucount = ulist->size();
1913 for (unsigned int i = 0; i < ucount; i++)
1915 char* o = (*ulist)[i];
1916 userrec* otheruser = (userrec*)o;
1917 if (std::string(otheruser->server) != Srv->GetServerName())
1919 TreeServer* best = BestRouteTo(otheruser->server);
1921 AddThisServer(best,list);
1927 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, std::string command, std::deque<std::string> ¶ms)
1929 TreeServer* omitroute = BestRouteTo(omit);
1930 if ((command == "NOTICE") || (command == "PRIVMSG"))
1932 if ((params.size() >= 2) && (*(params[0].c_str()) != '$'))
1934 if (*(params[0].c_str()) != '#')
1936 // special routing for private messages/notices
1937 userrec* d = Srv->FindNick(params[0]);
1940 std::deque<std::string> par;
1941 par.push_back(params[0]);
1942 par.push_back(":"+params[1]);
1943 DoOneToOne(prefix,command,par,d->server);
1949 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
1950 chanrec* c = Srv->FindChannel(params[0]);
1953 std::deque<TreeServer*> list;
1954 GetListOfServersForChannel(c,list);
1955 log(DEBUG,"Got a list of %d servers",list.size());
1956 unsigned int lsize = list.size();
1957 for (unsigned int i = 0; i < lsize; i++)
1959 TreeSocket* Sock = list[i]->GetSocket();
1960 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
1962 log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
1963 Sock->WriteLine(data);
1971 unsigned int items = TreeRoot->ChildCount();
1972 for (unsigned int x = 0; x < items; x++)
1974 TreeServer* Route = TreeRoot->GetChild(x);
1975 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1977 TreeSocket* Sock = Route->GetSocket();
1978 Sock->WriteLine(data);
1984 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string omit)
1986 TreeServer* omitroute = BestRouteTo(omit);
1987 std::string FullLine = ":" + prefix + " " + command;
1988 unsigned int words = params.size();
1989 for (unsigned int x = 0; x < words; x++)
1991 FullLine = FullLine + " " + params[x];
1993 unsigned int items = TreeRoot->ChildCount();
1994 for (unsigned int x = 0; x < items; x++)
1996 TreeServer* Route = TreeRoot->GetChild(x);
1997 // Send the line IF:
1998 // The route has a socket (its a direct connection)
1999 // The route isnt the one to be omitted
2000 // The route isnt the path to the one to be omitted
2001 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
2003 TreeSocket* Sock = Route->GetSocket();
2004 Sock->WriteLine(FullLine);
2010 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> ¶ms)
2012 std::string FullLine = ":" + prefix + " " + command;
2013 unsigned int words = params.size();
2014 for (unsigned int x = 0; x < words; x++)
2016 FullLine = FullLine + " " + params[x];
2018 unsigned int items = TreeRoot->ChildCount();
2019 for (unsigned int x = 0; x < items; x++)
2021 TreeServer* Route = TreeRoot->GetChild(x);
2022 if (Route->GetSocket())
2024 TreeSocket* Sock = Route->GetSocket();
2025 Sock->WriteLine(FullLine);
2031 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string target)
2033 TreeServer* Route = BestRouteTo(target);
2036 std::string FullLine = ":" + prefix + " " + command;
2037 unsigned int words = params.size();
2038 for (unsigned int x = 0; x < words; x++)
2040 FullLine = FullLine + " " + params[x];
2042 if (Route->GetSocket())
2044 TreeSocket* Sock = Route->GetSocket();
2045 Sock->WriteLine(FullLine);
2055 std::vector<TreeSocket*> Bindings;
2057 void ReadConfiguration(bool rebind)
2059 Conf = new ConfigReader;
2062 for (int j =0; j < Conf->Enumerate("bind"); j++)
2064 std::string Type = Conf->ReadValue("bind","type",j);
2065 std::string IP = Conf->ReadValue("bind","address",j);
2066 long Port = Conf->ReadInteger("bind","port",j,true);
2067 if (Type == "servers")
2073 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
2074 if (listener->GetState() == I_LISTENING)
2076 Srv->AddSocket(listener);
2077 Bindings.push_back(listener);
2081 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
2089 for (int j =0; j < Conf->Enumerate("link"); j++)
2092 L.Name = Conf->ReadValue("link","name",j);
2093 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
2094 L.Port = Conf->ReadInteger("link","port",j,true);
2095 L.SendPass = Conf->ReadValue("link","sendpass",j);
2096 L.RecvPass = Conf->ReadValue("link","recvpass",j);
2097 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
2098 L.NextConnectTime = time(NULL) + L.AutoConnect;
2099 LinkBlocks.push_back(L);
2100 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
2106 class ModuleSpanningTree : public Module
2108 std::vector<TreeSocket*> Bindings;
2114 ModuleSpanningTree(Server* Me)
2115 : Module::Module(Me)
2120 // Create the root of the tree
2121 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
2123 ReadConfiguration(true);
2126 void ShowLinks(TreeServer* Current, userrec* user, int hops)
2128 std::string Parent = TreeRoot->GetName();
2129 if (Current->GetParent())
2131 Parent = Current->GetParent()->GetName();
2133 for (unsigned int q = 0; q < Current->ChildCount(); q++)
2135 ShowLinks(Current->GetChild(q),user,hops+1);
2137 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
2140 int CountLocalServs()
2142 return TreeRoot->ChildCount();
2147 return serverlist.size();
2150 void HandleLinks(char** parameters, int pcnt, userrec* user)
2152 ShowLinks(TreeRoot,user,0);
2153 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
2157 void HandleLusers(char** parameters, int pcnt, userrec* user)
2159 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),this->CountServs());
2160 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
2161 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
2162 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
2163 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
2167 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
2169 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
2173 for (int t = 0; t < depth; t++)
2175 matrix[line][t] = ' ';
2177 strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
2179 for (unsigned int q = 0; q < Current->ChildCount(); q++)
2181 ShowMap(Current->GetChild(q),user,depth+2,matrix);
2186 // Ok, prepare to be confused.
2187 // After much mulling over how to approach this, it struck me that
2188 // the 'usual' way of doing a /MAP isnt the best way. Instead of
2189 // keeping track of a ton of ascii characters, and line by line
2190 // under recursion working out where to place them using multiplications
2191 // and divisons, we instead render the map onto a backplane of characters
2192 // (a character matrix), then draw the branches as a series of "L" shapes
2193 // from the nodes. This is not only friendlier on CPU it uses less stack.
2195 void HandleMap(char** parameters, int pcnt, userrec* user)
2197 // This array represents a virtual screen which we will
2198 // "scratch" draw to, as the console device of an irc
2199 // client does not provide for a proper terminal.
2200 char matrix[128][80];
2201 for (unsigned int t = 0; t < 128; t++)
2203 matrix[t][0] = '\0';
2206 // The only recursive bit is called here.
2207 ShowMap(TreeRoot,user,0,matrix);
2208 // Process each line one by one. The algorithm has a limit of
2209 // 128 servers (which is far more than a spanning tree should have
2210 // anyway, so we're ok). This limit can be raised simply by making
2211 // the character matrix deeper, 128 rows taking 10k of memory.
2212 for (int l = 1; l < line; l++)
2214 // scan across the line looking for the start of the
2215 // servername (the recursive part of the algorithm has placed
2216 // the servers at indented positions depending on what they
2218 int first_nonspace = 0;
2219 while (matrix[l][first_nonspace] == ' ')
2224 // Draw the `- (corner) section: this may be overwritten by
2225 // another L shape passing along the same vertical pane, becoming
2226 // a |- (branch) section instead.
2227 matrix[l][first_nonspace] = '-';
2228 matrix[l][first_nonspace-1] = '`';
2230 // Draw upwards until we hit the parent server, causing possibly
2231 // other corners (`-) to become branches (|-)
2232 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
2234 matrix[l2][first_nonspace-1] = '|';
2238 // dump the whole lot to the user. This is the easy bit, honest.
2239 for (int t = 0; t < line; t++)
2241 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
2243 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
2247 int HandleSquit(char** parameters, int pcnt, userrec* user)
2249 TreeServer* s = FindServerMask(parameters[0]);
2252 TreeSocket* sock = s->GetSocket();
2255 WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
2256 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
2261 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
2266 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
2271 int HandleRemoteWhois(char** parameters, int pcnt, userrec* user)
2273 if ((std::string(user->server) == Srv->GetServerName()) && (pcnt > 1))
2275 if (Srv->FindNick(parameters[1]))
2277 std::deque<std::string> params;
2278 params.push_back(parameters[1]);
2279 DoOneToMany(user->nick,"IDLE",params);
2284 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
2285 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
2292 void DoPingChecks(time_t curtime)
2294 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
2296 TreeServer* serv = TreeRoot->GetChild(j);
2297 TreeSocket* sock = serv->GetSocket();
2300 if (curtime >= serv->NextPingTime())
2302 if (serv->AnsweredLastPing())
2304 sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
2305 serv->SetNextPingTime(curtime + 60);
2309 // they didnt answer, boot them
2310 WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
2311 sock->Squit(serv,"Ping timeout");
2320 void AutoConnectServers(time_t curtime)
2322 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2324 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
2326 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
2327 x->NextConnectTime = curtime + x->AutoConnect;
2328 TreeServer* CheckDupe = FindServer(x->Name);
2331 // an autoconnected server is not connected. Check if its time to connect it
2332 WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
2333 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2334 Srv->AddSocket(newsocket);
2340 int HandleVersion(char** parameters, int pcnt, userrec* user)
2342 // we've already checked if pcnt > 0, so this is safe
2343 TreeServer* found = FindServerMask(parameters[0]);
2346 std::string Version = found->GetVersion();
2347 WriteServ(user->fd,"351 %s :%s",user->nick,Version.c_str());
2351 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
2356 int HandleConnect(char** parameters, int pcnt, userrec* user)
2358 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2360 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
2362 TreeServer* CheckDupe = FindServer(x->Name);
2365 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);
2366 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2367 Srv->AddSocket(newsocket);
2372 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());
2377 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
2381 virtual bool HandleStats(char ** parameters, int pcnt, userrec* user)
2383 if (*parameters[0] == 'c')
2385 for (unsigned int i = 0; i < LinkBlocks.size(); i++)
2387 WriteServ(user->fd,"213 %s C *@%s * %s %d 0 M",user->nick,LinkBlocks[i].IPAddr.c_str(),LinkBlocks[i].Name.c_str(),LinkBlocks[i].Port);
2388 WriteServ(user->fd,"244 %s H * * %s",user->nick,LinkBlocks[i].Name.c_str());
2390 WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
2391 WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
2397 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
2399 if (command == "CONNECT")
2401 return this->HandleConnect(parameters,pcnt,user);
2403 else if (command == "SQUIT")
2405 return this->HandleSquit(parameters,pcnt,user);
2407 else if (command == "STATS")
2409 return this->HandleStats(parameters,pcnt,user);
2411 else if (command == "MAP")
2413 this->HandleMap(parameters,pcnt,user);
2416 else if (command == "LUSERS")
2418 this->HandleLusers(parameters,pcnt,user);
2421 else if (command == "LINKS")
2423 this->HandleLinks(parameters,pcnt,user);
2426 else if (command == "WHOIS")
2431 return this->HandleRemoteWhois(parameters,pcnt,user);
2434 else if ((command == "VERSION") && (pcnt > 0))
2436 this->HandleVersion(parameters,pcnt,user);
2439 else if (Srv->IsValidModuleCommand(command, pcnt, user))
2441 // this bit of code cleverly routes all module commands
2442 // to all remote severs *automatically* so that modules
2443 // can just handle commands locally, without having
2444 // to have any special provision in place for remote
2445 // commands and linking protocols.
2446 std::deque<std::string> params;
2448 for (int j = 0; j < pcnt; j++)
2450 if (strchr(parameters[j],' '))
2452 params.push_back(":" + std::string(parameters[j]));
2456 params.push_back(std::string(parameters[j]));
2459 DoOneToMany(user->nick,command,params);
2464 virtual void OnGetServerDescription(std::string servername,std::string &description)
2466 TreeServer* s = FindServer(servername);
2469 description = s->GetDesc();
2473 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
2475 if (std::string(source->server) == Srv->GetServerName())
2477 std::deque<std::string> params;
2478 params.push_back(dest->nick);
2479 params.push_back(channel->name);
2480 DoOneToMany(source->nick,"INVITE",params);
2484 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
2486 std::deque<std::string> params;
2487 params.push_back(chan->name);
2488 params.push_back(":"+topic);
2489 DoOneToMany(user->nick,"TOPIC",params);
2492 virtual void OnWallops(userrec* user, std::string text)
2494 if (std::string(user->server) == Srv->GetServerName())
2496 std::deque<std::string> params;
2497 params.push_back(":"+text);
2498 DoOneToMany(user->nick,"WALLOPS",params);
2502 virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
2504 if (target_type == TYPE_USER)
2506 userrec* d = (userrec*)dest;
2507 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
2509 std::deque<std::string> params;
2511 params.push_back(d->nick);
2512 params.push_back(":"+text);
2513 DoOneToOne(user->nick,"NOTICE",params,d->server);
2518 if (std::string(user->server) == Srv->GetServerName())
2520 chanrec *c = (chanrec*)dest;
2521 std::deque<TreeServer*> list;
2522 GetListOfServersForChannel(c,list);
2523 unsigned int ucount = list.size();
2524 for (unsigned int i = 0; i < ucount; i++)
2526 TreeSocket* Sock = list[i]->GetSocket();
2528 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+std::string(c->name)+" :"+text);
2534 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
2536 if (target_type == TYPE_USER)
2538 // route private messages which are targetted at clients only to the server
2539 // which needs to receive them
2540 userrec* d = (userrec*)dest;
2541 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
2543 std::deque<std::string> params;
2545 params.push_back(d->nick);
2546 params.push_back(":"+text);
2547 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
2552 if (std::string(user->server) == Srv->GetServerName())
2554 chanrec *c = (chanrec*)dest;
2555 std::deque<TreeServer*> list;
2556 GetListOfServersForChannel(c,list);
2557 unsigned int ucount = list.size();
2558 for (unsigned int i = 0; i < ucount; i++)
2560 TreeSocket* Sock = list[i]->GetSocket();
2562 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+std::string(c->name)+" :"+text);
2568 virtual void OnBackgroundTimer(time_t curtime)
2570 AutoConnectServers(curtime);
2571 DoPingChecks(curtime);
2574 virtual void OnUserJoin(userrec* user, chanrec* channel)
2576 // Only do this for local users
2577 if (std::string(user->server) == Srv->GetServerName())
2579 std::deque<std::string> params;
2581 params.push_back(channel->name);
2584 // if the channel has a key, force the join by emulating the key.
2585 params.push_back(channel->key);
2587 if (channel->GetUserCounter() > 1)
2589 // not the first in the channel
2590 DoOneToMany(user->nick,"JOIN",params);
2594 // first in the channel, set up their permissions
2595 // and the channel TS with FJOIN.
2597 snprintf(ts,24,"%lu",(unsigned long)channel->age);
2599 params.push_back(channel->name);
2600 params.push_back(ts);
2601 params.push_back("@"+std::string(user->nick));
2602 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
2607 virtual void OnChangeHost(userrec* user, std::string newhost)
2609 // only occurs for local clients
2610 if (user->registered != 7)
2612 std::deque<std::string> params;
2613 params.push_back(newhost);
2614 DoOneToMany(user->nick,"FHOST",params);
2617 virtual void OnChangeName(userrec* user, std::string gecos)
2619 // only occurs for local clients
2620 if (user->registered != 7)
2622 std::deque<std::string> params;
2623 params.push_back(gecos);
2624 DoOneToMany(user->nick,"FNAME",params);
2627 virtual void OnUserPart(userrec* user, chanrec* channel)
2629 if (std::string(user->server) == Srv->GetServerName())
2631 std::deque<std::string> params;
2632 params.push_back(channel->name);
2633 DoOneToMany(user->nick,"PART",params);
2637 virtual void OnUserConnect(userrec* user)
2639 char agestr[MAXBUF];
2640 if (std::string(user->server) == Srv->GetServerName())
2642 std::deque<std::string> params;
2643 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
2644 params.push_back(agestr);
2645 params.push_back(user->nick);
2646 params.push_back(user->host);
2647 params.push_back(user->dhost);
2648 params.push_back(user->ident);
2649 params.push_back("+"+std::string(user->modes));
2650 params.push_back(user->ip);
2651 params.push_back(":"+std::string(user->fullname));
2652 DoOneToMany(Srv->GetServerName(),"NICK",params);
2656 virtual void OnUserQuit(userrec* user, std::string reason)
2658 if ((std::string(user->server) == Srv->GetServerName()) && (user->registered == 7))
2660 std::deque<std::string> params;
2661 params.push_back(":"+reason);
2662 DoOneToMany(user->nick,"QUIT",params);
2666 virtual void OnUserPostNick(userrec* user, std::string oldnick)
2668 if (std::string(user->server) == Srv->GetServerName())
2670 std::deque<std::string> params;
2671 params.push_back(user->nick);
2672 DoOneToMany(oldnick,"NICK",params);
2676 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
2678 if (std::string(source->server) == Srv->GetServerName())
2680 std::deque<std::string> params;
2681 params.push_back(chan->name);
2682 params.push_back(user->nick);
2683 params.push_back(":"+reason);
2684 DoOneToMany(source->nick,"KICK",params);
2688 virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
2690 std::deque<std::string> params;
2691 params.push_back(dest->nick);
2692 params.push_back(":"+reason);
2693 DoOneToMany(source->nick,"KILL",params);
2696 virtual void OnRehash(std::string parameter)
2698 if (parameter != "")
2700 std::deque<std::string> params;
2701 params.push_back(parameter);
2702 DoOneToMany(Srv->GetServerName(),"REHASH",params);
2704 if (Srv->MatchText(Srv->GetServerName(),parameter))
2706 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
2707 Srv->RehashServer();
2710 ReadConfiguration(false);
2713 // note: the protocol does not allow direct umode +o except
2714 // via NICK with 8 params. sending OPERTYPE infers +o modechange
2716 virtual void OnOper(userrec* user, std::string opertype)
2718 if (std::string(user->server) == Srv->GetServerName())
2720 std::deque<std::string> params;
2721 params.push_back(opertype);
2722 DoOneToMany(user->nick,"OPERTYPE",params);
2726 void OnLine(userrec* source, std::string host, bool adding, char linetype, long duration, std::string reason)
2728 if (std::string(source->server) == Srv->GetServerName())
2731 snprintf(type,8,"%cLINE",linetype);
2732 std::string stype = type;
2735 char sduration[MAXBUF];
2736 snprintf(sduration,MAXBUF,"%ld",duration);
2737 std::deque<std::string> params;
2738 params.push_back(host);
2739 params.push_back(sduration);
2740 params.push_back(":"+reason);
2741 DoOneToMany(source->nick,stype,params);
2745 std::deque<std::string> params;
2746 params.push_back(host);
2747 DoOneToMany(source->nick,stype,params);
2752 virtual void OnAddGLine(long duration, userrec* source, std::string reason, std::string hostmask)
2754 OnLine(source,hostmask,true,'G',duration,reason);
2757 virtual void OnAddZLine(long duration, userrec* source, std::string reason, std::string ipmask)
2759 OnLine(source,ipmask,true,'Z',duration,reason);
2762 virtual void OnAddQLine(long duration, userrec* source, std::string reason, std::string nickmask)
2764 OnLine(source,nickmask,true,'Q',duration,reason);
2767 virtual void OnAddELine(long duration, userrec* source, std::string reason, std::string hostmask)
2769 OnLine(source,hostmask,true,'E',duration,reason);
2772 virtual void OnDelGLine(userrec* source, std::string hostmask)
2774 OnLine(source,hostmask,false,'G',0,"");
2777 virtual void OnDelZLine(userrec* source, std::string ipmask)
2779 OnLine(source,ipmask,false,'Z',0,"");
2782 virtual void OnDelQLine(userrec* source, std::string nickmask)
2784 OnLine(source,nickmask,false,'Q',0,"");
2787 virtual void OnDelELine(userrec* source, std::string hostmask)
2789 OnLine(source,hostmask,false,'E',0,"");
2792 virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
2794 if ((std::string(user->server) == Srv->GetServerName()) && (user->registered == 7))
2796 if (target_type == TYPE_USER)
2798 userrec* u = (userrec*)dest;
2799 std::deque<std::string> params;
2800 params.push_back(u->nick);
2801 params.push_back(text);
2802 DoOneToMany(user->nick,"MODE",params);
2806 chanrec* c = (chanrec*)dest;
2807 std::deque<std::string> params;
2808 params.push_back(c->name);
2809 params.push_back(text);
2810 DoOneToMany(user->nick,"MODE",params);
2815 virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
2817 TreeSocket* s = (TreeSocket*)opaque;
2820 if (target_type == TYPE_USER)
2822 userrec* u = (userrec*)target;
2823 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
2827 chanrec* c = (chanrec*)target;
2828 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
2833 virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, std::string extname, std::string extdata)
2835 TreeSocket* s = (TreeSocket*)opaque;
2838 if (target_type == TYPE_USER)
2840 userrec* u = (userrec*)target;
2841 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+u->nick+" "+extname+" :"+extdata);
2845 chanrec* c = (chanrec*)target;
2846 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+c->name+" "+extname+" :"+extdata);
2851 virtual ~ModuleSpanningTree()
2855 virtual Version GetVersion()
2857 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
2862 class ModuleSpanningTreeFactory : public ModuleFactory
2865 ModuleSpanningTreeFactory()
2869 ~ModuleSpanningTreeFactory()
2873 virtual Module * CreateModule(Server* Me)
2875 TreeProtocolModule = new ModuleSpanningTree(Me);
2876 return TreeProtocolModule;
2882 extern "C" void * init_module( void )
2884 return new ModuleSpanningTreeFactory;