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 log(DEBUG,"In IDLE command");
1370 userrec* u = Srv->FindNick(prefix);
1373 log(DEBUG,"USER EXISTS: %s",u->nick);
1374 // an incoming request
1375 if (params.size() == 1)
1377 if (std::string(u->server) != Srv->GetServerName())
1379 userrec* x = Srv->FindNick(params[0]);
1380 log(DEBUG,"Got IDLE, sending back IDLE");
1381 char signon[MAXBUF];
1383 if ((x) && (std::string(x->server) == Srv->GetServerName()))
1385 snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
1386 snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-time(NULL)));
1387 std::deque<std::string> par;
1388 par.push_back(prefix);
1389 par.push_back(signon);
1390 par.push_back(idle);
1391 DoOneToOne(params[0],"IDLE",par,u->server);
1395 // not for us, pass it on
1396 DoOneToOne(prefix,"IDLE",params,u->server);
1401 DoOneToOne(prefix,"IDLE",params,u->server);
1404 else if (params.size() == 3)
1406 if (std::string(u->server) != Srv->GetServerName())
1408 log(DEBUG,"Got final IDLE");
1409 // an incoming reply to a whois we sent out
1410 std::string nick_whoised = prefix;
1411 std::string who_did_the_whois = params[0];
1412 unsigned long signon = atoi(params[1].c_str());
1413 unsigned long idle = atoi(params[2].c_str());
1414 userrec* who_to_send_to = Srv->FindNick(who_did_the_whois);
1415 if ((who_to_send_to) && (std::string(who_to_send_to->server) == Srv->GetServerName()))
1416 do_whois(who_to_send_to,u,signon,idle,(char*)nick_whoised.c_str());
1420 DoOneToOne(prefix,"IDLE",params,u->server);
1427 bool LocalPing(std::string prefix, std::deque<std::string> ¶ms)
1429 if (params.size() < 1)
1431 std::string stufftobounce = params[0];
1432 this->WriteLine(":"+Srv->GetServerName()+" PONG "+stufftobounce);
1436 bool RemoteServer(std::string prefix, std::deque<std::string> ¶ms)
1438 if (params.size() < 4)
1440 std::string servername = params[0];
1441 std::string password = params[1];
1442 // hopcount is not used for a remote server, we calculate this ourselves
1443 std::string description = params[3];
1444 TreeServer* ParentOfThis = FindServer(prefix);
1447 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
1450 TreeServer* CheckDupe = FindServer(servername);
1453 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1456 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
1457 ParentOfThis->AddChild(Node);
1458 params[3] = ":" + params[3];
1459 DoOneToAllButSender(prefix,"SERVER",params,prefix);
1460 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
1464 bool Outbound_Reply_Server(std::deque<std::string> ¶ms)
1466 if (params.size() < 4)
1468 std::string servername = params[0];
1469 std::string password = params[1];
1470 int hops = atoi(params[2].c_str());
1473 this->WriteLine("ERROR :Server too far away for authentication");
1476 std::string description = params[3];
1477 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1479 if ((x->Name == servername) && (x->RecvPass == password))
1481 TreeServer* CheckDupe = FindServer(servername);
1484 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1487 // Begin the sync here. this kickstarts the
1488 // other side, waiting in WAIT_AUTH_2 state,
1489 // into starting their burst, as it shows
1490 // that we're happy.
1491 this->LinkState = CONNECTED;
1492 // we should add the details of this server now
1493 // to the servers tree, as a child of the root
1495 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
1496 TreeRoot->AddChild(Node);
1497 params[3] = ":" + params[3];
1498 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
1499 this->bursting = true;
1500 this->DoBurst(Node);
1504 this->WriteLine("ERROR :Invalid credentials");
1508 bool Inbound_Server(std::deque<std::string> ¶ms)
1510 if (params.size() < 4)
1512 std::string servername = params[0];
1513 std::string password = params[1];
1514 int hops = atoi(params[2].c_str());
1517 this->WriteLine("ERROR :Server too far away for authentication");
1520 std::string description = params[3];
1521 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1523 if ((x->Name == servername) && (x->RecvPass == password))
1525 TreeServer* CheckDupe = FindServer(servername);
1528 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1531 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
1532 this->InboundServerName = servername;
1533 this->InboundDescription = description;
1534 // this is good. Send our details: Our server name and description and hopcount of 0,
1535 // along with the sendpass from this block.
1536 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
1537 // move to the next state, we are now waiting for THEM.
1538 this->LinkState = WAIT_AUTH_2;
1542 this->WriteLine("ERROR :Invalid credentials");
1546 void Split(std::string line, bool stripcolon, std::deque<std::string> &n)
1548 if (!strchr(line.c_str(),' '))
1553 std::stringstream s(line);
1554 std::string param = "";
1573 if ((param == ":") && (item > 0))
1596 bool ProcessLine(std::string line)
1598 char* l = (char*)line.c_str();
1599 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
1600 l[strlen(l)-1] = '\0';
1604 Srv->Log(DEBUG,"IN: '"+line+"'");
1605 std::deque<std::string> params;
1606 this->Split(line,true,params);
1607 std::string command = "";
1608 std::string prefix = "";
1609 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
1612 command = params[1];
1613 char* pref = (char*)prefix.c_str();
1621 command = params[0];
1625 switch (this->LinkState)
1630 // Waiting for SERVER command from remote server. Server initiating
1631 // the connection sends the first SERVER command, listening server
1632 // replies with theirs if its happy, then if the initiator is happy,
1633 // it starts to send its net sync, which starts the merge, otherwise
1634 // it sends an ERROR.
1635 if (command == "SERVER")
1637 return this->Inbound_Server(params);
1639 else if (command == "ERROR")
1641 return this->Error(params);
1645 // Waiting for start of other side's netmerge to say they liked our
1647 if (command == "SERVER")
1649 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1653 else if (command == "BURST")
1655 this->LinkState = CONNECTED;
1656 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
1657 TreeRoot->AddChild(Node);
1659 params.push_back(InboundServerName);
1660 params.push_back("*");
1661 params.push_back("1");
1662 params.push_back(":"+InboundDescription);
1663 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
1664 this->bursting = true;
1665 this->DoBurst(Node);
1667 else if (command == "ERROR")
1669 return this->Error(params);
1674 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
1678 if (command == "SERVER")
1680 // another server we connected to, which was in WAIT_AUTH_1 state,
1681 // has just sent us their credentials. If we get this far, theyre
1682 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1683 // if we're happy with this, we should send our netburst which
1684 // kickstarts the merge.
1685 return this->Outbound_Reply_Server(params);
1687 else if (command == "ERROR")
1689 return this->Error(params);
1693 // This is the 'authenticated' state, when all passwords
1694 // have been exchanged and anything past this point is taken
1699 std::string direction = prefix;
1700 userrec* t = Srv->FindNick(prefix);
1703 direction = t->server;
1705 TreeServer* route_back_again = BestRouteTo(direction);
1706 if ((!route_back_again) || (route_back_again->GetSocket() != this))
1708 WriteOpers("*** \2WARNING\2! Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
1713 if (command == "SVSMODE")
1715 /* Services expects us to implement
1716 * SVSMODE. In inspircd its the same as
1721 std::string target = "";
1722 /* Yes, know, this is a mess. Its reasonably fast though as we're
1723 * working with std::string here.
1725 if ((command == "NICK") && (params.size() > 1))
1727 return this->IntroduceClient(prefix,params);
1729 else if (command == "FJOIN")
1731 return this->ForceJoin(prefix,params);
1733 else if (command == "SERVER")
1735 return this->RemoteServer(prefix,params);
1737 else if (command == "ERROR")
1739 return this->Error(params);
1741 else if (command == "OPERTYPE")
1743 return this->OperType(prefix,params);
1745 else if (command == "FMODE")
1747 return this->ForceMode(prefix,params);
1749 else if (command == "KILL")
1751 return this->RemoteKill(prefix,params);
1753 else if (command == "FTOPIC")
1755 return this->ForceTopic(prefix,params);
1757 else if (command == "REHASH")
1759 return this->RemoteRehash(prefix,params);
1761 else if (command == "METADATA")
1763 return this->MetaData(prefix,params);
1765 else if (command == "PING")
1767 return this->LocalPing(prefix,params);
1769 else if (command == "PONG")
1771 return this->LocalPong(prefix,params);
1773 else if (command == "VERSION")
1775 return this->ServerVersion(prefix,params);
1777 else if (command == "FHOST")
1779 return this->ChangeHost(prefix,params);
1781 else if (command == "FNAME")
1783 return this->ChangeName(prefix,params);
1785 else if (command == "ADDLINE")
1787 return this->AddLine(prefix,params);
1789 else if (command == "SVSNICK")
1793 prefix = this->GetName();
1795 return this->ForceNick(prefix,params);
1797 else if (command == "IDLE")
1799 return this->Whois(prefix,params);
1801 else if (command == "SVSJOIN")
1805 prefix = this->GetName();
1807 return this->ServiceJoin(prefix,params);
1809 else if (command == "SQUIT")
1811 if (params.size() == 2)
1813 this->Squit(FindServer(params[0]),params[1]);
1817 else if (command == "ENDBURST")
1819 this->bursting = false;
1824 // not a special inter-server command.
1825 // Emulate the actual user doing the command,
1826 // this saves us having a huge ugly parser.
1827 userrec* who = Srv->FindNick(prefix);
1828 std::string sourceserv = this->myhost;
1829 if (this->InboundServerName != "")
1831 sourceserv = this->InboundServerName;
1836 target = who->server;
1837 char* strparams[127];
1838 for (unsigned int q = 0; q < params.size(); q++)
1840 strparams[q] = (char*)params[q].c_str();
1842 Srv->CallCommandHandler(command, strparams, params.size(), who);
1846 // its not a user. Its either a server, or somethings screwed up.
1847 if (IsServer(prefix))
1849 target = Srv->GetServerName();
1853 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
1857 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1866 virtual std::string GetName()
1868 std::string sourceserv = this->myhost;
1869 if (this->InboundServerName != "")
1871 sourceserv = this->InboundServerName;
1876 virtual void OnTimeout()
1878 if (this->LinkState == CONNECTING)
1880 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
1884 virtual void OnClose()
1886 // Connection closed.
1887 // If the connection is fully up (state CONNECTED)
1888 // then propogate a netsplit to all peers.
1889 std::string quitserver = this->myhost;
1890 if (this->InboundServerName != "")
1892 quitserver = this->InboundServerName;
1894 TreeServer* s = FindServer(quitserver);
1897 Squit(s,"Remote host closed the connection");
1901 virtual int OnIncomingConnection(int newsock, char* ip)
1903 TreeSocket* s = new TreeSocket(newsock, ip);
1909 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
1911 for (unsigned int c = 0; c < list.size(); c++)
1913 if (list[c] == server)
1918 list.push_back(server);
1921 // returns a list of DIRECT servernames for a specific channel
1922 void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
1924 std::vector<char*> *ulist = c->GetUsers();
1925 unsigned int ucount = ulist->size();
1926 for (unsigned int i = 0; i < ucount; i++)
1928 char* o = (*ulist)[i];
1929 userrec* otheruser = (userrec*)o;
1930 if (std::string(otheruser->server) != Srv->GetServerName())
1932 TreeServer* best = BestRouteTo(otheruser->server);
1934 AddThisServer(best,list);
1940 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, std::string command, std::deque<std::string> ¶ms)
1942 TreeServer* omitroute = BestRouteTo(omit);
1943 if ((command == "NOTICE") || (command == "PRIVMSG"))
1945 if ((params.size() >= 2) && (*(params[0].c_str()) != '$'))
1947 if (*(params[0].c_str()) != '#')
1949 // special routing for private messages/notices
1950 userrec* d = Srv->FindNick(params[0]);
1953 std::deque<std::string> par;
1954 par.push_back(params[0]);
1955 par.push_back(":"+params[1]);
1956 DoOneToOne(prefix,command,par,d->server);
1962 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
1963 chanrec* c = Srv->FindChannel(params[0]);
1966 std::deque<TreeServer*> list;
1967 GetListOfServersForChannel(c,list);
1968 log(DEBUG,"Got a list of %d servers",list.size());
1969 unsigned int lsize = list.size();
1970 for (unsigned int i = 0; i < lsize; i++)
1972 TreeSocket* Sock = list[i]->GetSocket();
1973 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
1975 log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
1976 Sock->WriteLine(data);
1984 unsigned int items = TreeRoot->ChildCount();
1985 for (unsigned int x = 0; x < items; x++)
1987 TreeServer* Route = TreeRoot->GetChild(x);
1988 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1990 TreeSocket* Sock = Route->GetSocket();
1991 Sock->WriteLine(data);
1997 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string omit)
1999 TreeServer* omitroute = BestRouteTo(omit);
2000 std::string FullLine = ":" + prefix + " " + command;
2001 unsigned int words = params.size();
2002 for (unsigned int x = 0; x < words; x++)
2004 FullLine = FullLine + " " + params[x];
2006 unsigned int items = TreeRoot->ChildCount();
2007 for (unsigned int x = 0; x < items; x++)
2009 TreeServer* Route = TreeRoot->GetChild(x);
2010 // Send the line IF:
2011 // The route has a socket (its a direct connection)
2012 // The route isnt the one to be omitted
2013 // The route isnt the path to the one to be omitted
2014 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
2016 TreeSocket* Sock = Route->GetSocket();
2017 Sock->WriteLine(FullLine);
2023 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> ¶ms)
2025 std::string FullLine = ":" + prefix + " " + command;
2026 unsigned int words = params.size();
2027 for (unsigned int x = 0; x < words; x++)
2029 FullLine = FullLine + " " + params[x];
2031 unsigned int items = TreeRoot->ChildCount();
2032 for (unsigned int x = 0; x < items; x++)
2034 TreeServer* Route = TreeRoot->GetChild(x);
2035 if (Route->GetSocket())
2037 TreeSocket* Sock = Route->GetSocket();
2038 Sock->WriteLine(FullLine);
2044 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string target)
2046 TreeServer* Route = BestRouteTo(target);
2049 std::string FullLine = ":" + prefix + " " + command;
2050 unsigned int words = params.size();
2051 for (unsigned int x = 0; x < words; x++)
2053 FullLine = FullLine + " " + params[x];
2055 if (Route->GetSocket())
2057 TreeSocket* Sock = Route->GetSocket();
2058 Sock->WriteLine(FullLine);
2068 std::vector<TreeSocket*> Bindings;
2070 void ReadConfiguration(bool rebind)
2072 Conf = new ConfigReader;
2075 for (int j =0; j < Conf->Enumerate("bind"); j++)
2077 std::string Type = Conf->ReadValue("bind","type",j);
2078 std::string IP = Conf->ReadValue("bind","address",j);
2079 long Port = Conf->ReadInteger("bind","port",j,true);
2080 if (Type == "servers")
2086 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
2087 if (listener->GetState() == I_LISTENING)
2089 Srv->AddSocket(listener);
2090 Bindings.push_back(listener);
2094 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
2102 for (int j =0; j < Conf->Enumerate("link"); j++)
2105 L.Name = Conf->ReadValue("link","name",j);
2106 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
2107 L.Port = Conf->ReadInteger("link","port",j,true);
2108 L.SendPass = Conf->ReadValue("link","sendpass",j);
2109 L.RecvPass = Conf->ReadValue("link","recvpass",j);
2110 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
2111 L.NextConnectTime = time(NULL) + L.AutoConnect;
2112 LinkBlocks.push_back(L);
2113 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
2119 class ModuleSpanningTree : public Module
2121 std::vector<TreeSocket*> Bindings;
2127 ModuleSpanningTree(Server* Me)
2128 : Module::Module(Me)
2133 // Create the root of the tree
2134 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
2136 ReadConfiguration(true);
2139 void ShowLinks(TreeServer* Current, userrec* user, int hops)
2141 std::string Parent = TreeRoot->GetName();
2142 if (Current->GetParent())
2144 Parent = Current->GetParent()->GetName();
2146 for (unsigned int q = 0; q < Current->ChildCount(); q++)
2148 ShowLinks(Current->GetChild(q),user,hops+1);
2150 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
2153 int CountLocalServs()
2155 return TreeRoot->ChildCount();
2160 return serverlist.size();
2163 void HandleLinks(char** parameters, int pcnt, userrec* user)
2165 ShowLinks(TreeRoot,user,0);
2166 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
2170 void HandleLusers(char** parameters, int pcnt, userrec* user)
2172 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),this->CountServs());
2173 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
2174 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
2175 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
2176 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
2180 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
2182 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
2186 for (int t = 0; t < depth; t++)
2188 matrix[line][t] = ' ';
2190 strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
2192 for (unsigned int q = 0; q < Current->ChildCount(); q++)
2194 ShowMap(Current->GetChild(q),user,depth+2,matrix);
2199 // Ok, prepare to be confused.
2200 // After much mulling over how to approach this, it struck me that
2201 // the 'usual' way of doing a /MAP isnt the best way. Instead of
2202 // keeping track of a ton of ascii characters, and line by line
2203 // under recursion working out where to place them using multiplications
2204 // and divisons, we instead render the map onto a backplane of characters
2205 // (a character matrix), then draw the branches as a series of "L" shapes
2206 // from the nodes. This is not only friendlier on CPU it uses less stack.
2208 void HandleMap(char** parameters, int pcnt, userrec* user)
2210 // This array represents a virtual screen which we will
2211 // "scratch" draw to, as the console device of an irc
2212 // client does not provide for a proper terminal.
2213 char matrix[128][80];
2214 for (unsigned int t = 0; t < 128; t++)
2216 matrix[t][0] = '\0';
2219 // The only recursive bit is called here.
2220 ShowMap(TreeRoot,user,0,matrix);
2221 // Process each line one by one. The algorithm has a limit of
2222 // 128 servers (which is far more than a spanning tree should have
2223 // anyway, so we're ok). This limit can be raised simply by making
2224 // the character matrix deeper, 128 rows taking 10k of memory.
2225 for (int l = 1; l < line; l++)
2227 // scan across the line looking for the start of the
2228 // servername (the recursive part of the algorithm has placed
2229 // the servers at indented positions depending on what they
2231 int first_nonspace = 0;
2232 while (matrix[l][first_nonspace] == ' ')
2237 // Draw the `- (corner) section: this may be overwritten by
2238 // another L shape passing along the same vertical pane, becoming
2239 // a |- (branch) section instead.
2240 matrix[l][first_nonspace] = '-';
2241 matrix[l][first_nonspace-1] = '`';
2243 // Draw upwards until we hit the parent server, causing possibly
2244 // other corners (`-) to become branches (|-)
2245 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
2247 matrix[l2][first_nonspace-1] = '|';
2251 // dump the whole lot to the user. This is the easy bit, honest.
2252 for (int t = 0; t < line; t++)
2254 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
2256 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
2260 int HandleSquit(char** parameters, int pcnt, userrec* user)
2262 TreeServer* s = FindServerMask(parameters[0]);
2265 TreeSocket* sock = s->GetSocket();
2268 WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
2269 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
2274 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
2279 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
2284 int HandleRemoteWhois(char** parameters, int pcnt, userrec* user)
2286 if ((std::string(user->server) == Srv->GetServerName()) && (pcnt > 1))
2288 userrec* remote = Srv->FindNick(parameters[1]);
2289 if ((remote) && (std::string(remote->server) != Srv->GetServerName()))
2291 std::deque<std::string> params;
2292 params.push_back(parameters[1]);
2293 DoOneToOne(user->nick,"IDLE",params,remote->server);
2298 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
2299 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
2306 void DoPingChecks(time_t curtime)
2308 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
2310 TreeServer* serv = TreeRoot->GetChild(j);
2311 TreeSocket* sock = serv->GetSocket();
2314 if (curtime >= serv->NextPingTime())
2316 if (serv->AnsweredLastPing())
2318 sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
2319 serv->SetNextPingTime(curtime + 60);
2323 // they didnt answer, boot them
2324 WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
2325 sock->Squit(serv,"Ping timeout");
2334 void AutoConnectServers(time_t curtime)
2336 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2338 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
2340 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
2341 x->NextConnectTime = curtime + x->AutoConnect;
2342 TreeServer* CheckDupe = FindServer(x->Name);
2345 // an autoconnected server is not connected. Check if its time to connect it
2346 WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
2347 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2348 Srv->AddSocket(newsocket);
2354 int HandleVersion(char** parameters, int pcnt, userrec* user)
2356 // we've already checked if pcnt > 0, so this is safe
2357 TreeServer* found = FindServerMask(parameters[0]);
2360 std::string Version = found->GetVersion();
2361 WriteServ(user->fd,"351 %s :%s",user->nick,Version.c_str());
2365 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
2370 int HandleConnect(char** parameters, int pcnt, userrec* user)
2372 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2374 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
2376 TreeServer* CheckDupe = FindServer(x->Name);
2379 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);
2380 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2381 Srv->AddSocket(newsocket);
2386 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());
2391 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
2395 virtual bool HandleStats(char ** parameters, int pcnt, userrec* user)
2397 if (*parameters[0] == 'c')
2399 for (unsigned int i = 0; i < LinkBlocks.size(); i++)
2401 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);
2402 WriteServ(user->fd,"244 %s H * * %s",user->nick,LinkBlocks[i].Name.c_str());
2404 WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
2405 WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
2411 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
2413 if (command == "CONNECT")
2415 return this->HandleConnect(parameters,pcnt,user);
2417 else if (command == "SQUIT")
2419 return this->HandleSquit(parameters,pcnt,user);
2421 else if (command == "STATS")
2423 return this->HandleStats(parameters,pcnt,user);
2425 else if (command == "MAP")
2427 this->HandleMap(parameters,pcnt,user);
2430 else if (command == "LUSERS")
2432 this->HandleLusers(parameters,pcnt,user);
2435 else if (command == "LINKS")
2437 this->HandleLinks(parameters,pcnt,user);
2440 else if (command == "WHOIS")
2445 return this->HandleRemoteWhois(parameters,pcnt,user);
2448 else if ((command == "VERSION") && (pcnt > 0))
2450 this->HandleVersion(parameters,pcnt,user);
2453 else if (Srv->IsValidModuleCommand(command, pcnt, user))
2455 // this bit of code cleverly routes all module commands
2456 // to all remote severs *automatically* so that modules
2457 // can just handle commands locally, without having
2458 // to have any special provision in place for remote
2459 // commands and linking protocols.
2460 std::deque<std::string> params;
2462 for (int j = 0; j < pcnt; j++)
2464 if (strchr(parameters[j],' '))
2466 params.push_back(":" + std::string(parameters[j]));
2470 params.push_back(std::string(parameters[j]));
2473 DoOneToMany(user->nick,command,params);
2478 virtual void OnGetServerDescription(std::string servername,std::string &description)
2480 TreeServer* s = FindServer(servername);
2483 description = s->GetDesc();
2487 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
2489 if (std::string(source->server) == Srv->GetServerName())
2491 std::deque<std::string> params;
2492 params.push_back(dest->nick);
2493 params.push_back(channel->name);
2494 DoOneToMany(source->nick,"INVITE",params);
2498 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
2500 std::deque<std::string> params;
2501 params.push_back(chan->name);
2502 params.push_back(":"+topic);
2503 DoOneToMany(user->nick,"TOPIC",params);
2506 virtual void OnWallops(userrec* user, std::string text)
2508 if (std::string(user->server) == Srv->GetServerName())
2510 std::deque<std::string> params;
2511 params.push_back(":"+text);
2512 DoOneToMany(user->nick,"WALLOPS",params);
2516 virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
2518 if (target_type == TYPE_USER)
2520 userrec* d = (userrec*)dest;
2521 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
2523 std::deque<std::string> params;
2525 params.push_back(d->nick);
2526 params.push_back(":"+text);
2527 DoOneToOne(user->nick,"NOTICE",params,d->server);
2532 if (std::string(user->server) == Srv->GetServerName())
2534 chanrec *c = (chanrec*)dest;
2535 std::deque<TreeServer*> list;
2536 GetListOfServersForChannel(c,list);
2537 unsigned int ucount = list.size();
2538 for (unsigned int i = 0; i < ucount; i++)
2540 TreeSocket* Sock = list[i]->GetSocket();
2542 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+std::string(c->name)+" :"+text);
2548 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
2550 if (target_type == TYPE_USER)
2552 // route private messages which are targetted at clients only to the server
2553 // which needs to receive them
2554 userrec* d = (userrec*)dest;
2555 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
2557 std::deque<std::string> params;
2559 params.push_back(d->nick);
2560 params.push_back(":"+text);
2561 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
2566 if (std::string(user->server) == Srv->GetServerName())
2568 chanrec *c = (chanrec*)dest;
2569 std::deque<TreeServer*> list;
2570 GetListOfServersForChannel(c,list);
2571 unsigned int ucount = list.size();
2572 for (unsigned int i = 0; i < ucount; i++)
2574 TreeSocket* Sock = list[i]->GetSocket();
2576 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+std::string(c->name)+" :"+text);
2582 virtual void OnBackgroundTimer(time_t curtime)
2584 AutoConnectServers(curtime);
2585 DoPingChecks(curtime);
2588 virtual void OnUserJoin(userrec* user, chanrec* channel)
2590 // Only do this for local users
2591 if (std::string(user->server) == Srv->GetServerName())
2593 std::deque<std::string> params;
2595 params.push_back(channel->name);
2598 // if the channel has a key, force the join by emulating the key.
2599 params.push_back(channel->key);
2601 if (channel->GetUserCounter() > 1)
2603 // not the first in the channel
2604 DoOneToMany(user->nick,"JOIN",params);
2608 // first in the channel, set up their permissions
2609 // and the channel TS with FJOIN.
2611 snprintf(ts,24,"%lu",(unsigned long)channel->age);
2613 params.push_back(channel->name);
2614 params.push_back(ts);
2615 params.push_back("@"+std::string(user->nick));
2616 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
2621 virtual void OnChangeHost(userrec* user, std::string newhost)
2623 // only occurs for local clients
2624 if (user->registered != 7)
2626 std::deque<std::string> params;
2627 params.push_back(newhost);
2628 DoOneToMany(user->nick,"FHOST",params);
2631 virtual void OnChangeName(userrec* user, std::string gecos)
2633 // only occurs for local clients
2634 if (user->registered != 7)
2636 std::deque<std::string> params;
2637 params.push_back(gecos);
2638 DoOneToMany(user->nick,"FNAME",params);
2641 virtual void OnUserPart(userrec* user, chanrec* channel)
2643 if (std::string(user->server) == Srv->GetServerName())
2645 std::deque<std::string> params;
2646 params.push_back(channel->name);
2647 DoOneToMany(user->nick,"PART",params);
2651 virtual void OnUserConnect(userrec* user)
2653 char agestr[MAXBUF];
2654 if (std::string(user->server) == Srv->GetServerName())
2656 std::deque<std::string> params;
2657 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
2658 params.push_back(agestr);
2659 params.push_back(user->nick);
2660 params.push_back(user->host);
2661 params.push_back(user->dhost);
2662 params.push_back(user->ident);
2663 params.push_back("+"+std::string(user->modes));
2664 params.push_back(user->ip);
2665 params.push_back(":"+std::string(user->fullname));
2666 DoOneToMany(Srv->GetServerName(),"NICK",params);
2670 virtual void OnUserQuit(userrec* user, std::string reason)
2672 if ((std::string(user->server) == Srv->GetServerName()) && (user->registered == 7))
2674 std::deque<std::string> params;
2675 params.push_back(":"+reason);
2676 DoOneToMany(user->nick,"QUIT",params);
2680 virtual void OnUserPostNick(userrec* user, std::string oldnick)
2682 if (std::string(user->server) == Srv->GetServerName())
2684 std::deque<std::string> params;
2685 params.push_back(user->nick);
2686 DoOneToMany(oldnick,"NICK",params);
2690 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
2692 if (std::string(source->server) == Srv->GetServerName())
2694 std::deque<std::string> params;
2695 params.push_back(chan->name);
2696 params.push_back(user->nick);
2697 params.push_back(":"+reason);
2698 DoOneToMany(source->nick,"KICK",params);
2702 virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
2704 std::deque<std::string> params;
2705 params.push_back(dest->nick);
2706 params.push_back(":"+reason);
2707 DoOneToMany(source->nick,"KILL",params);
2710 virtual void OnRehash(std::string parameter)
2712 if (parameter != "")
2714 std::deque<std::string> params;
2715 params.push_back(parameter);
2716 DoOneToMany(Srv->GetServerName(),"REHASH",params);
2718 if (Srv->MatchText(Srv->GetServerName(),parameter))
2720 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
2721 Srv->RehashServer();
2724 ReadConfiguration(false);
2727 // note: the protocol does not allow direct umode +o except
2728 // via NICK with 8 params. sending OPERTYPE infers +o modechange
2730 virtual void OnOper(userrec* user, std::string opertype)
2732 if (std::string(user->server) == Srv->GetServerName())
2734 std::deque<std::string> params;
2735 params.push_back(opertype);
2736 DoOneToMany(user->nick,"OPERTYPE",params);
2740 void OnLine(userrec* source, std::string host, bool adding, char linetype, long duration, std::string reason)
2742 if (std::string(source->server) == Srv->GetServerName())
2745 snprintf(type,8,"%cLINE",linetype);
2746 std::string stype = type;
2749 char sduration[MAXBUF];
2750 snprintf(sduration,MAXBUF,"%ld",duration);
2751 std::deque<std::string> params;
2752 params.push_back(host);
2753 params.push_back(sduration);
2754 params.push_back(":"+reason);
2755 DoOneToMany(source->nick,stype,params);
2759 std::deque<std::string> params;
2760 params.push_back(host);
2761 DoOneToMany(source->nick,stype,params);
2766 virtual void OnAddGLine(long duration, userrec* source, std::string reason, std::string hostmask)
2768 OnLine(source,hostmask,true,'G',duration,reason);
2771 virtual void OnAddZLine(long duration, userrec* source, std::string reason, std::string ipmask)
2773 OnLine(source,ipmask,true,'Z',duration,reason);
2776 virtual void OnAddQLine(long duration, userrec* source, std::string reason, std::string nickmask)
2778 OnLine(source,nickmask,true,'Q',duration,reason);
2781 virtual void OnAddELine(long duration, userrec* source, std::string reason, std::string hostmask)
2783 OnLine(source,hostmask,true,'E',duration,reason);
2786 virtual void OnDelGLine(userrec* source, std::string hostmask)
2788 OnLine(source,hostmask,false,'G',0,"");
2791 virtual void OnDelZLine(userrec* source, std::string ipmask)
2793 OnLine(source,ipmask,false,'Z',0,"");
2796 virtual void OnDelQLine(userrec* source, std::string nickmask)
2798 OnLine(source,nickmask,false,'Q',0,"");
2801 virtual void OnDelELine(userrec* source, std::string hostmask)
2803 OnLine(source,hostmask,false,'E',0,"");
2806 virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
2808 if ((std::string(user->server) == Srv->GetServerName()) && (user->registered == 7))
2810 if (target_type == TYPE_USER)
2812 userrec* u = (userrec*)dest;
2813 std::deque<std::string> params;
2814 params.push_back(u->nick);
2815 params.push_back(text);
2816 DoOneToMany(user->nick,"MODE",params);
2820 chanrec* c = (chanrec*)dest;
2821 std::deque<std::string> params;
2822 params.push_back(c->name);
2823 params.push_back(text);
2824 DoOneToMany(user->nick,"MODE",params);
2829 virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
2831 TreeSocket* s = (TreeSocket*)opaque;
2834 if (target_type == TYPE_USER)
2836 userrec* u = (userrec*)target;
2837 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
2841 chanrec* c = (chanrec*)target;
2842 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
2847 virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, std::string extname, std::string extdata)
2849 TreeSocket* s = (TreeSocket*)opaque;
2852 if (target_type == TYPE_USER)
2854 userrec* u = (userrec*)target;
2855 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+u->nick+" "+extname+" :"+extdata);
2859 chanrec* c = (chanrec*)target;
2860 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+c->name+" "+extname+" :"+extdata);
2865 virtual ~ModuleSpanningTree()
2869 virtual Version GetVersion()
2871 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
2876 class ModuleSpanningTreeFactory : public ModuleFactory
2879 ModuleSpanningTreeFactory()
2883 ~ModuleSpanningTreeFactory()
2887 virtual Module * CreateModule(Server* Me)
2889 TreeProtocolModule = new ModuleSpanningTree(Me);
2890 return TreeProtocolModule;
2896 extern "C" void * init_module( void )
2898 return new ModuleSpanningTreeFactory;