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"
45 #define nspace __gnu_cxx
51 * The server list in InspIRCd is maintained as two structures
52 * which hold the data in different ways. Most of the time, we
53 * want to very quicky obtain three pieces of information:
55 * (1) The information on a server
56 * (2) The information on the server we must send data through
57 * to actually REACH the server we're after
58 * (3) Potentially, the child/parent objects of this server
60 * The InspIRCd spanning protocol provides easy access to these
61 * by storing the data firstly in a recursive structure, where
62 * each item references its parent item, and a dynamic list
63 * of child items, and another structure which stores the items
64 * hashed, linearly. This means that if we want to find a server
65 * by name quickly, we can look it up in the hash, avoiding
66 * any O(n) lookups. If however, during a split or sync, we want
67 * to apply an operation to a server, and any of its child objects
68 * we can resort to recursion to walk the tree structure.
71 class ModuleSpanningTree;
72 static ModuleSpanningTree* TreeProtocolModule;
74 extern std::vector<Module*> modules;
75 extern std::vector<ircd_module*> factory;
78 /* Any socket can have one of five states at any one time.
79 * The LISTENER state indicates a socket which is listening
80 * for connections. It cannot receive data itself, only incoming
82 * The CONNECTING state indicates an outbound socket which is
83 * waiting to be writeable.
84 * The WAIT_AUTH_1 state indicates the socket is outbound and
85 * has successfully connected, but has not yet sent and received
87 * The WAIT_AUTH_2 state indicates that the socket is inbound
88 * (allocated by a LISTENER) but has not yet sent and received
90 * The CONNECTED state represents a fully authorized, fully
93 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
95 /* We need to import these from the core for use in netbursts */
96 /*typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
97 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;*/
98 extern user_hash clientlist;
99 extern chan_hash chanlist;
101 /* Foward declarations */
105 /* This variable represents the root of the server tree
106 * (for all intents and purposes, it's us)
108 TreeServer *TreeRoot;
112 /* This hash_map holds the hash equivalent of the server
113 * tree, used for rapid linear lookups.
115 typedef nspace::hash_map<std::string, TreeServer*> server_hash;
116 server_hash serverlist;
118 /* More forward declarations */
119 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string target);
120 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string omit);
121 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> ¶ms);
122 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, std::string command, std::deque<std::string> ¶ms);
123 void ReadConfiguration(bool rebind);
125 /* Imported from xline.cpp for use during netburst */
126 extern std::vector<KLine> klines;
127 extern std::vector<GLine> glines;
128 extern std::vector<ZLine> zlines;
129 extern std::vector<QLine> qlines;
130 extern std::vector<ELine> elines;
131 extern std::vector<KLine> pklines;
132 extern std::vector<GLine> pglines;
133 extern std::vector<ZLine> pzlines;
134 extern std::vector<QLine> pqlines;
135 extern std::vector<ELine> pelines;
137 /* Each server in the tree is represented by one class of
138 * type TreeServer. A locally connected TreeServer can
139 * have a class of type TreeSocket associated with it, for
140 * remote servers, the TreeSocket entry will be NULL.
141 * Each server also maintains a pointer to its parent
142 * (NULL if this server is ours, at the top of the tree)
143 * and a pointer to its "Route" (see the comments in the
144 * constructors below), and also a dynamic list of pointers
145 * to its children which can be iterated recursively
146 * if required. Creating or deleting objects of type
147 * TreeServer automatically maintains the hash_map of
148 * TreeServer items, deleting and inserting them as they
149 * are created and destroyed.
154 TreeServer* Parent; /* Parent entry */
155 TreeServer* Route; /* Route entry */
156 std::vector<TreeServer*> Children; /* List of child objects */
157 std::string ServerName; /* Server's name */
158 std::string ServerDesc; /* Server's description */
159 std::string VersionString; /* Version string or empty string */
160 int UserCount; /* Not used in this version */
161 int OperCount; /* Not used in this version */
162 TreeSocket* Socket; /* For directly connected servers this points at the socket object */
163 time_t NextPing; /* After this time, the server should be PINGed*/
164 bool LastPingWasGood; /* True if the server responded to the last PING with a PONG */
168 /* We don't use this constructor. Its a dummy, and won't cause any insertion
169 * of the TreeServer into the hash_map. See below for the two we DO use.
177 UserCount = OperCount = 0;
178 VersionString = Srv->GetVersion();
181 /* We use this constructor only to create the 'root' item, TreeRoot, which
182 * represents our own server. Therefore, it has no route, no parent, and
183 * no socket associated with it. Its version string is our own local version.
185 TreeServer(std::string Name, std::string Desc) : ServerName(Name), ServerDesc(Desc)
189 UserCount = OperCount = 0;
190 VersionString = Srv->GetVersion();
195 /* When we create a new server, we call this constructor to initialize it.
196 * This constructor initializes the server's Route and Parent, and sets up
197 * its ping counters so that it will be pinged one minute from now.
199 TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name), ServerDesc(Desc), Socket(Sock)
202 UserCount = OperCount = 0;
203 this->SetNextPingTime(time(NULL) + 60);
206 /* find the 'route' for this server (e.g. the one directly connected
207 * to the local server, which we can use to reach it)
209 * In the following example, consider we have just added a TreeServer
210 * class for server G on our network, of which we are server A.
211 * To route traffic to G (marked with a *) we must send the data to
212 * B (marked with a +) so this algorithm initializes the 'Route'
213 * value to point at whichever server traffic must be routed through
214 * to get here. If we were to try this algorithm with server B,
215 * the Route pointer would point at its own object ('this').
225 * We only run this algorithm when a server is created, as
226 * the routes remain constant while ever the server exists, and
227 * do not need to be re-calculated.
231 if (Route == TreeRoot)
237 while (this->Route->GetParent() != TreeRoot)
239 this->Route = Route->GetParent();
243 /* Because recursive code is slow and takes a lot of resources,
244 * we store two representations of the server tree. The first
245 * is a recursive structure where each server references its
246 * children and its parent, which is used for netbursts and
247 * netsplits to dump the whole dataset to the other server,
248 * and the second is used for very fast lookups when routing
249 * messages and is instead a hash_map, where each item can
250 * be referenced by its server name. The AddHashEntry()
251 * call below automatically inserts each TreeServer class
252 * into the hash_map as it is created. There is a similar
253 * maintainance call in the destructor to tidy up deleted
257 this->AddHashEntry();
260 /* This method is used to add the structure to the
261 * hash_map for linear searches. It is only called
262 * by the constructors.
266 server_hash::iterator iter;
267 iter = serverlist.find(this->ServerName);
268 if (iter == serverlist.end())
269 serverlist[this->ServerName] = this;
272 /* This method removes the reference to this object
273 * from the hash_map which is used for linear searches.
274 * It is only called by the default destructor.
278 server_hash::iterator iter;
279 iter = serverlist.find(this->ServerName);
280 if (iter != serverlist.end())
281 serverlist.erase(iter);
284 /* These accessors etc should be pretty self-
288 TreeServer* GetRoute()
293 std::string GetName()
295 return this->ServerName;
298 std::string GetDesc()
300 return this->ServerDesc;
303 std::string GetVersion()
305 return this->VersionString;
308 void SetNextPingTime(time_t t)
311 LastPingWasGood = false;
314 time_t NextPingTime()
316 return this->NextPing;
319 bool AnsweredLastPing()
321 return LastPingWasGood;
326 LastPingWasGood = true;
331 return this->UserCount;
336 return this->OperCount;
339 TreeSocket* GetSocket()
344 TreeServer* GetParent()
349 void SetVersion(std::string Version)
351 VersionString = Version;
354 unsigned int ChildCount()
356 return Children.size();
359 TreeServer* GetChild(unsigned int n)
361 if (n < Children.size())
363 /* Make sure they cant request
364 * an out-of-range object. After
365 * all we know what these programmer
366 * types are like *grin*.
376 void AddChild(TreeServer* Child)
378 Children.push_back(Child);
381 bool DelChild(TreeServer* Child)
383 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
394 /* Removes child nodes of this node, and of that node, etc etc.
395 * This is used during netsplits to automatically tidy up the
396 * server tree. It is slow, we don't use it for much else.
400 bool stillchildren = true;
401 while (stillchildren)
403 stillchildren = false;
404 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
406 TreeServer* s = (TreeServer*)*a;
410 stillchildren = true;
419 /* We'd better tidy up after ourselves, eh? */
420 this->DelHashEntry();
424 /* The Link class might as well be a struct,
425 * but this is C++ and we don't believe in structs (!).
426 * It holds the entire information of one <link>
427 * tag from the main config file. We maintain a list
428 * of them, and populate the list on rehash/load.
437 std::string SendPass;
438 std::string RecvPass;
439 unsigned long AutoConnect;
440 time_t NextConnectTime;
443 /* The usual stuff for inspircd modules,
444 * plus the vector of Link classes which we
445 * use to store the <link> tags from the config
449 std::vector<Link> LinkBlocks;
451 /* Yay for fast searches!
452 * This is hundreds of times faster than recursion
453 * or even scanning a linked list, especially when
454 * there are more than a few servers to deal with.
457 TreeServer* FindServer(std::string ServerName)
459 server_hash::iterator iter;
460 iter = serverlist.find(ServerName);
461 if (iter != serverlist.end())
471 /* Returns the locally connected server we must route a
472 * message through to reach server 'ServerName'. This
473 * only applies to one-to-one and not one-to-many routing.
474 * See the comments for the constructor of TreeServer
477 TreeServer* BestRouteTo(std::string ServerName)
479 if (ServerName.c_str() == TreeRoot->GetName())
481 TreeServer* Found = FindServer(ServerName);
484 return Found->GetRoute();
492 /* Find the first server matching a given glob mask.
493 * Theres no find-using-glob method of hash_map [awwww :-(]
494 * so instead, we iterate over the list using an iterator
495 * and match each one until we get a hit. Yes its slow,
498 TreeServer* FindServerMask(std::string ServerName)
500 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
502 if (Srv->MatchText(i->first,ServerName))
508 /* A convenient wrapper that returns true if a server exists */
509 bool IsServer(std::string ServerName)
511 return (FindServer(ServerName) != NULL);
514 /* Every SERVER connection inbound or outbound is represented by
515 * an object of type TreeSocket.
516 * TreeSockets, being inherited from InspSocket, can be tied into
517 * the core socket engine, and we cn therefore receive activity events
518 * for them, just like activex objects on speed. (yes really, that
519 * is a technical term!) Each of these which relates to a locally
520 * connected server is assocated with it, by hooking it onto a
521 * TreeSocket class using its constructor. In this way, we can
522 * maintain a list of servers, some of which are directly connected,
523 * some of which are not.
526 class TreeSocket : public InspSocket
529 std::string in_buffer;
530 ServerState LinkState;
531 std::string InboundServerName;
532 std::string InboundDescription;
534 int num_lost_servers;
536 bool LastPingWasGood;
541 /* Because most of the I/O gubbins are encapsulated within
542 * InspSocket, we just call the superclass constructor for
543 * most of the action, and append a few of our own values
546 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
547 : InspSocket(host, port, listening, maxtime)
550 this->LinkState = LISTENER;
553 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
554 : InspSocket(host, port, listening, maxtime)
557 this->LinkState = CONNECTING;
560 /* When a listening socket gives us a new file descriptor,
561 * we must associate it with a socket without creating a new
562 * connection. This constructor is used for this purpose.
564 TreeSocket(int newfd, char* ip)
565 : InspSocket(newfd, ip)
567 this->LinkState = WAIT_AUTH_1;
570 /* When an outbound connection finishes connecting, we receive
571 * this event, and must send our SERVER string to the other
572 * side. If the other side is happy, as outlined in the server
573 * to server docs on the inspircd.org site, the other side
574 * will then send back its own server string.
576 virtual bool OnConnected()
578 if (this->LinkState == CONNECTING)
580 Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
581 /* we do not need to change state here. */
582 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
584 if (x->Name == this->myhost)
586 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
587 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
592 /* There is a (remote) chance that between the /CONNECT and the connection
593 * being accepted, some muppet has removed the <link> block and rehashed.
594 * If that happens the connection hangs here until it's closed. Unlikely
595 * and rather harmless.
600 virtual void OnError(InspSocketError e)
602 /* We don't handle this method, because all our
603 * dirty work is done in OnClose() (see below)
604 * which is still called on error conditions too.
608 virtual int OnDisconnect()
610 /* For the same reason as above, we don't
611 * handle OnDisconnect()
616 /* Recursively send the server tree with distances as hops.
617 * This is used during network burst to inform the other server
618 * (and any of ITS servers too) of what servers we know about.
619 * If at any point any of these servers already exist on the other
620 * end, our connection may be terminated. The hopcounts given
621 * by this function are relative, this doesn't matter so long as
622 * they are all >1, as all the remote servers re-calculate them
623 * to be relative too, with themselves as hop 0.
625 void SendServers(TreeServer* Current, TreeServer* s, int hops)
628 for (unsigned int q = 0; q < Current->ChildCount(); q++)
630 TreeServer* recursive_server = Current->GetChild(q);
631 if (recursive_server != s)
633 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
634 this->WriteLine(command);
635 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
636 /* down to next level */
637 this->SendServers(recursive_server, s, hops+1);
642 /* This function forces this server to quit, removing this server
643 * and any users on it (and servers and users below that, etc etc).
644 * It's very slow and pretty clunky, but luckily unless your network
645 * is having a REAL bad hair day, this function shouldnt be called
646 * too many times a month ;-)
648 void SquitServer(TreeServer* Current)
650 /* recursively squit the servers attached to 'Current'.
651 * We're going backwards so we don't remove users
652 * while we still need them ;)
654 for (unsigned int q = 0; q < Current->ChildCount(); q++)
656 TreeServer* recursive_server = Current->GetChild(q);
657 this->SquitServer(recursive_server);
659 /* Now we've whacked the kids, whack self */
661 bool quittingpeople = true;
662 while (quittingpeople)
664 /* Yup i know, "ew". We cant continue to loop through the
665 * iterator if we modify it, so whenever we modify it with a
666 * QUIT we have to start alllll over again. If anyone knows
667 * a better faster way of *safely* doing this, please let me
670 quittingpeople = false;
671 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
673 if (!strcasecmp(u->second->server,Current->GetName().c_str()))
675 Srv->QuitUser(u->second,Current->GetName()+" "+std::string(Srv->GetServerName()));
677 quittingpeople = true;
684 /* This is a wrapper function for SquitServer above, which
685 * does some validation first and passes on the SQUIT to all
686 * other remaining servers.
688 void Squit(TreeServer* Current,std::string reason)
692 std::deque<std::string> params;
693 params.push_back(Current->GetName());
694 params.push_back(":"+reason);
695 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
696 if (Current->GetParent() == TreeRoot)
698 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
702 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
704 num_lost_servers = 0;
706 SquitServer(Current);
708 Current->GetParent()->DelChild(Current);
710 WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
714 log(DEFAULT,"Squit from unknown server");
719 bool ForceMode(std::string source, std::deque<std::string> params)
721 userrec* who = new userrec;
722 who->fd = FD_MAGIC_NUMBER;
723 if (params.size() < 2)
726 for (unsigned int q = 0; q < params.size(); q++)
728 modelist[q] = (char*)params[q].c_str();
730 Srv->SendMode(modelist,params.size(),who);
731 DoOneToAllButSender(source,"FMODE",params,source);
737 bool ForceTopic(std::string source, std::deque<std::string> params)
739 if (params.size() != 4)
741 std::string channel = params[0];
742 time_t ts = atoi(params[1].c_str());
743 std::string setby = params[2];
744 std::string topic = params[3];
746 chanrec* c = Srv->FindChannel(channel);
749 if ((ts >= c->topicset) || (!*c->topic))
751 std::string oldtopic = c->topic;
752 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
753 strlcpy(c->setby,setby.c_str(),NICKMAX);
755 /* if the topic text is the same as the current topic,
756 * dont bother to send the TOPIC command out, just silently
757 * update the set time and set nick.
759 if (oldtopic != topic)
760 WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
765 /* all done, send it on its way */
766 params[3] = ":" + params[3];
767 DoOneToAllButSender(source,"FTOPIC",params,source);
772 /* FJOIN, similar to unreal SJOIN */
773 bool ForceJoin(std::string source, std::deque<std::string> params)
775 if (params.size() < 3)
779 char modestring[MAXBUF];
780 char* mode_users[127];
781 mode_users[0] = first;
782 mode_users[1] = modestring;
783 strcpy(mode_users[1],"+");
784 unsigned int modectr = 2;
787 std::string channel = params[0];
788 time_t TS = atoi(params[1].c_str());
791 chanrec* chan = Srv->FindChannel(channel);
796 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
798 /* default is a high value, which if we dont have this
799 * channel will let the other side apply their modes.
801 time_t ourTS = time(NULL)+600;
802 chanrec* us = Srv->FindChannel(channel);
808 log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
810 /* do this first, so our mode reversals are correctly received by other servers
811 * if there is a TS collision.
813 DoOneToAllButSender(source,"FJOIN",params,source);
815 for (unsigned int usernum = 2; usernum < params.size(); usernum++)
817 /* process one channel at a time, applying modes. */
818 char* usr = (char*)params[usernum].c_str();
819 char permissions = *usr;
824 mode_users[modectr++] = usr;
825 strlcat(modestring,"o",MAXBUF);
829 mode_users[modectr++] = usr;
830 strlcat(modestring,"h",MAXBUF);
834 mode_users[modectr++] = usr;
835 strlcat(modestring,"v",MAXBUF);
838 who = Srv->FindNick(usr);
841 Srv->JoinUserToChannel(who,channel,key);
842 if (modectr >= (MAXMODES-1))
844 /* theres a mode for this user. push them onto the mode queue, and flush it
845 * if there are more than MAXMODES to go.
847 if ((ourTS >= TS) || (Srv->IsUlined(who->server)))
849 /* We also always let u-lined clients win, no matter what the TS value */
850 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
851 Srv->SendMode(mode_users,modectr,who);
855 log(DEBUG,"Their channel newer than ours, bouncing their modes");
857 std::deque<std::string> params;
858 /* modes are now being UNSET... */
859 *mode_users[1] = '-';
860 for (unsigned int x = 0; x < modectr; x++)
862 params.push_back(mode_users[x]);
864 // tell everyone to bounce the modes. bad modes, bad!
865 DoOneToMany(Srv->GetServerName(),"FMODE",params);
867 strcpy(mode_users[1],"+");
872 /* there werent enough modes built up to flush it during FJOIN,
873 * or, there are a number left over. flush them out.
875 if ((modectr > 2) && (who))
879 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
880 Srv->SendMode(mode_users,modectr,who);
884 log(DEBUG,"Their channel newer than ours, bouncing their modes");
885 std::deque<std::string> params;
886 *mode_users[1] = '-';
887 for (unsigned int x = 0; x < modectr; x++)
889 params.push_back(mode_users[x]);
891 DoOneToMany(Srv->GetServerName(),"FMODE",params);
898 bool IntroduceClient(std::string source, std::deque<std::string> params)
900 if (params.size() < 8)
902 // NICK age nick host dhost ident +modes ip :gecos
904 std::string nick = params[1];
905 std::string host = params[2];
906 std::string dhost = params[3];
907 std::string ident = params[4];
908 time_t age = atoi(params[0].c_str());
909 std::string modes = params[5];
910 while (*(modes.c_str()) == '+')
912 char* m = (char*)modes.c_str();
916 std::string ip = params[6];
917 std::string gecos = params[7];
918 char* tempnick = (char*)nick.c_str();
919 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
921 user_hash::iterator iter;
922 iter = clientlist.find(tempnick);
923 if (iter != clientlist.end())
926 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);
927 this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
931 clientlist[tempnick] = new userrec();
932 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
933 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
934 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
935 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
936 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
937 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
938 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
939 clientlist[tempnick]->registered = 7;
940 clientlist[tempnick]->signon = age;
941 strlcpy(clientlist[tempnick]->modes, modes.c_str(),53);
942 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
947 for (int i = 0; i < MAXCHANS; i++)
948 clientlist[tempnick]->chans.push_back(a);
952 WriteOpers("*** Client connecting at %s: %s!%s@%s [%s]",clientlist[tempnick]->server,clientlist[tempnick]->nick,clientlist[tempnick]->ident,clientlist[tempnick]->host,clientlist[tempnick]->ip);
954 params[7] = ":" + params[7];
955 DoOneToAllButSender(source,"NICK",params,source);
959 /* Send one or more FJOINs for a channel of users.
960 * If the length of a single line is more than 480-NICKMAX
961 * in length, it is split over multiple lines.
963 void SendFJoins(TreeServer* Current, chanrec* c)
965 log(DEBUG,"Sending FJOINs to other server for %s",c->name);
967 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
968 std::vector<char*> *ulist = c->GetUsers();
969 for (unsigned int i = 0; i < ulist->size(); i++)
971 char* o = (*ulist)[i];
972 userrec* otheruser = (userrec*)o;
973 strlcat(list," ",MAXBUF);
974 strlcat(list,cmode(otheruser,c),MAXBUF);
975 strlcat(list,otheruser->nick,MAXBUF);
976 if (strlen(list)>(480-NICKMAX))
978 log(DEBUG,"FJOIN line wrapped");
979 this->WriteLine(list);
980 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
983 if (list[strlen(list)-1] != ':')
985 log(DEBUG,"Final FJOIN line");
986 this->WriteLine(list);
990 /* Send G, Q, Z and E lines */
991 void SendXLines(TreeServer* Current)
994 /* Yes, these arent too nice looking, but they get the job done */
995 for (std::vector<ZLine>::iterator i = zlines.begin(); i != zlines.end(); i++)
997 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);
998 this->WriteLine(data);
1000 for (std::vector<QLine>::iterator i = qlines.begin(); i != qlines.end(); i++)
1002 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);
1003 this->WriteLine(data);
1005 for (std::vector<GLine>::iterator i = glines.begin(); i != glines.end(); i++)
1007 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);
1008 this->WriteLine(data);
1010 for (std::vector<ELine>::iterator i = elines.begin(); i != elines.end(); i++)
1012 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);
1013 this->WriteLine(data);
1015 for (std::vector<ZLine>::iterator i = pzlines.begin(); i != pzlines.end(); i++)
1017 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);
1018 this->WriteLine(data);
1020 for (std::vector<QLine>::iterator i = pqlines.begin(); i != pqlines.end(); i++)
1022 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);
1023 this->WriteLine(data);
1025 for (std::vector<GLine>::iterator i = pglines.begin(); i != pglines.end(); i++)
1027 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);
1028 this->WriteLine(data);
1030 for (std::vector<ELine>::iterator i = pelines.begin(); i != pelines.end(); i++)
1032 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);
1033 this->WriteLine(data);
1037 /* Send channel modes and topics */
1038 void SendChannelModes(TreeServer* Current)
1041 std::deque<std::string> list;
1042 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
1044 SendFJoins(Current, c->second);
1045 snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
1046 this->WriteLine(data);
1047 if (*c->second->topic)
1049 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);
1050 this->WriteLine(data);
1052 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
1054 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
1055 this->WriteLine(data);
1057 FOREACH_MOD OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this);
1059 c->second->GetExtList(list);
1060 for (unsigned int j = 0; j < list.size(); j++)
1062 FOREACH_MOD OnSyncChannelMetaData(c->second,(Module*)TreeProtocolModule,(void*)this,list[j]);
1067 /* send all users and their oper state/modes */
1068 void SendUsers(TreeServer* Current)
1071 std::deque<std::string> list;
1072 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
1074 if (u->second->registered == 7)
1076 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);
1077 this->WriteLine(data);
1078 if (strchr(u->second->modes,'o'))
1080 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
1082 FOREACH_MOD OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this);
1084 u->second->GetExtList(list);
1085 for (unsigned int j = 0; j < list.size(); j++)
1087 FOREACH_MOD OnSyncUserMetaData(u->second,(Module*)TreeProtocolModule,(void*)this,list[j]);
1093 /* This function is called when we want to send a netburst to a local
1094 * server. There is a set order we must do this, because for example
1095 * users require their servers to exist, and channels require their
1096 * users to exist. You get the idea.
1098 void DoBurst(TreeServer* s)
1100 Srv->SendOpers("*** Bursting to \2"+s->GetName()+"\2.");
1101 this->WriteLine("BURST");
1102 /* send our version string */
1103 this->WriteLine(":"+Srv->GetServerName()+" VERSION :"+Srv->GetVersion());
1104 /* Send server tree */
1105 this->SendServers(TreeRoot,s,1);
1106 /* Send users and their oper status */
1108 /* Send everything else (channel modes, xlines etc) */
1109 this->SendChannelModes(s);
1110 this->SendXLines(s);
1111 this->WriteLine("ENDBURST");
1112 Srv->SendOpers("*** Finished bursting to \2"+s->GetName()+"\2.");
1115 /* This function is called when we receive data from a remote
1116 * server. We buffer the data in a std::string (it doesnt stay
1117 * there for long), reading using InspSocket::Read() which can
1118 * read up to 16 kilobytes in one operation.
1120 * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
1121 * THE SOCKET OBJECT FOR US.
1123 virtual bool OnDataReady()
1125 char* data = this->Read();
1128 this->in_buffer += data;
1129 /* While there is at least one new line in the buffer,
1130 * do something useful (we hope!) with it.
1132 while (in_buffer.find("\n") != std::string::npos)
1134 char* line = (char*)in_buffer.c_str();
1135 std::string ret = "";
1136 while ((*line != '\n') && (strlen(line)))
1141 if ((*line == '\n') || (*line == '\r'))
1144 /* Process this one, abort if it
1145 * didnt return true.
1147 if (!this->ProcessLine(ret))
1153 return (data != NULL);
1156 int WriteLine(std::string line)
1158 log(DEBUG,"OUT: %s",line.c_str());
1159 return this->Write(line + "\r\n");
1162 /* Handle ERROR command */
1163 bool Error(std::deque<std::string> params)
1165 if (params.size() < 1)
1167 std::string Errmsg = params[0];
1168 std::string SName = myhost;
1169 if (InboundServerName != "")
1171 SName = InboundServerName;
1173 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
1174 /* we will return false to cause the socket to close.
1179 /* Because the core won't let users or even SERVERS set +o,
1180 * we use the OPERTYPE command to do this.
1182 bool OperType(std::string prefix, std::deque<std::string> ¶ms)
1184 if (params.size() != 1)
1186 std::string opertype = params[0];
1187 userrec* u = Srv->FindNick(prefix);
1190 strlcpy(u->oper,opertype.c_str(),NICKMAX);
1191 if (!strchr(u->modes,'o'))
1193 strcat(u->modes,"o");
1195 DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
1200 /* Because Andy insists that services-compatible servers must
1201 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
1203 bool ForceNick(std::string prefix, std::deque<std::string> ¶ms)
1205 if (params.size() < 3)
1207 userrec* u = Srv->FindNick(params[0]);
1210 Srv->ChangeUserNick(u,params[1]);
1211 u->age = atoi(params[2].c_str());
1212 DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
1217 bool ServiceJoin(std::string prefix, std::deque<std::string> ¶ms)
1219 if (params.size() < 2)
1221 userrec* u = Srv->FindNick(params[0]);
1224 Srv->JoinUserToChannel(u,params[1],"");
1225 DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
1230 bool RemoteRehash(std::string prefix, std::deque<std::string> ¶ms)
1232 if (params.size() < 1)
1234 std::string servermask = params[0];
1235 if (Srv->MatchText(Srv->GetServerName(),servermask))
1237 Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
1238 Srv->RehashServer();
1239 ReadConfiguration(false);
1241 DoOneToAllButSender(prefix,"REHASH",params,prefix);
1245 bool RemoteKill(std::string prefix, std::deque<std::string> ¶ms)
1247 if (params.size() != 2)
1249 std::string nick = params[0];
1250 userrec* u = Srv->FindNick(prefix);
1251 userrec* who = Srv->FindNick(nick);
1254 /* Prepend kill source, if we don't have one */
1255 std::string sourceserv = prefix;
1258 sourceserv = u->server;
1260 if (*(params[1].c_str()) != '[')
1262 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
1264 std::string reason = params[1];
1265 params[1] = ":" + params[1];
1266 DoOneToAllButSender(prefix,"KILL",params,sourceserv);
1267 Srv->QuitUser(who,reason);
1272 bool LocalPong(std::string prefix, std::deque<std::string> ¶ms)
1274 if (params.size() < 1)
1276 TreeServer* ServerSource = FindServer(prefix);
1279 ServerSource->SetPingFlag();
1284 bool MetaData(std::string prefix, std::deque<std::string> ¶ms)
1286 if (params.size() < 3)
1288 TreeServer* ServerSource = FindServer(prefix);
1291 if (*(params[0].c_str()) == '#')
1293 chanrec* c = Srv->FindChannel(params[0]);
1296 FOREACH_MOD OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]);
1301 userrec* u = Srv->FindNick(params[0]);
1304 FOREACH_MOD OnDecodeMetaData(TYPE_USER,u,params[1],params[2]);
1308 params[2] = ":" + params[2];
1309 DoOneToAllButSender(prefix,"METADATA",params,prefix);
1313 bool ServerVersion(std::string prefix, std::deque<std::string> ¶ms)
1315 if (params.size() < 1)
1317 TreeServer* ServerSource = FindServer(prefix);
1320 ServerSource->SetVersion(params[0]);
1322 params[0] = ":" + params[0];
1323 DoOneToAllButSender(prefix,"VERSION",params,prefix);
1327 bool ChangeHost(std::string prefix, std::deque<std::string> ¶ms)
1329 if (params.size() < 1)
1331 userrec* u = Srv->FindNick(prefix);
1334 Srv->ChangeHost(u,params[0]);
1335 DoOneToAllButSender(prefix,"FHOST",params,u->server);
1340 bool AddLine(std::string prefix, std::deque<std::string> ¶ms)
1342 if (params.size() < 6)
1344 std::string linetype = params[0]; /* Z, Q, E, G, K */
1345 std::string mask = params[1]; /* Line type dependent */
1346 std::string source = params[2]; /* may not be online or may be a server */
1347 std::string settime = params[3]; /* EPOCH time set */
1348 std::string duration = params[4]; /* Duration secs */
1349 std::string reason = params[5];
1351 switch (*(linetype.c_str()))
1354 add_zline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1355 zline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1358 add_qline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1359 qline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1362 add_eline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1363 eline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1366 add_gline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1367 gline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1370 add_kline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1373 /* Just in case... */
1374 Srv->SendOpers("*** \2WARNING\2: Invalid xline type '"+linetype+"' sent by server "+prefix+", ignored!");
1377 /* Send it on its way */
1378 params[5] = ":" + params[5];
1379 DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
1383 bool ChangeName(std::string prefix, std::deque<std::string> ¶ms)
1385 if (params.size() < 1)
1387 userrec* u = Srv->FindNick(prefix);
1390 Srv->ChangeGECOS(u,params[0]);
1391 params[0] = ":" + params[0];
1392 DoOneToAllButSender(prefix,"FNAME",params,u->server);
1397 bool Whois(std::string prefix, std::deque<std::string> ¶ms)
1399 if (params.size() < 1)
1401 log(DEBUG,"In IDLE command");
1402 userrec* u = Srv->FindNick(prefix);
1405 log(DEBUG,"USER EXISTS: %s",u->nick);
1406 // an incoming request
1407 if (params.size() == 1)
1409 userrec* x = Srv->FindNick(params[0]);
1412 userrec* x = Srv->FindNick(params[0]);
1413 log(DEBUG,"Got IDLE");
1414 char signon[MAXBUF];
1416 log(DEBUG,"Sending back IDLE 3");
1417 snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
1418 snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-time(NULL)));
1419 std::deque<std::string> par;
1420 par.push_back(prefix);
1421 par.push_back(signon);
1422 par.push_back(idle);
1423 // ours, we're done, pass it BACK
1424 DoOneToOne(params[0],"IDLE",par,u->server);
1428 // not ours pass it on
1429 DoOneToOne(prefix,"IDLE",params,x->server);
1432 else if (params.size() == 3)
1434 std::string who_did_the_whois = params[0];
1435 userrec* who_to_send_to = Srv->FindNick(who_did_the_whois);
1436 if (who_to_send_to->fd > -1)
1438 log(DEBUG,"Got final IDLE");
1439 // an incoming reply to a whois we sent out
1440 std::string nick_whoised = prefix;
1441 unsigned long signon = atoi(params[1].c_str());
1442 unsigned long idle = atoi(params[2].c_str());
1443 if ((who_to_send_to) && (who_to_send_to->fd > -1))
1444 do_whois(who_to_send_to,u,signon,idle,(char*)nick_whoised.c_str());
1448 // not ours, pass it on
1449 DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
1456 bool LocalPing(std::string prefix, std::deque<std::string> ¶ms)
1458 if (params.size() < 1)
1460 std::string stufftobounce = params[0];
1461 this->WriteLine(":"+Srv->GetServerName()+" PONG "+stufftobounce);
1465 bool RemoteServer(std::string prefix, std::deque<std::string> ¶ms)
1467 if (params.size() < 4)
1469 std::string servername = params[0];
1470 std::string password = params[1];
1471 // hopcount is not used for a remote server, we calculate this ourselves
1472 std::string description = params[3];
1473 TreeServer* ParentOfThis = FindServer(prefix);
1476 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
1479 TreeServer* CheckDupe = FindServer(servername);
1482 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1485 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
1486 ParentOfThis->AddChild(Node);
1487 params[3] = ":" + params[3];
1488 DoOneToAllButSender(prefix,"SERVER",params,prefix);
1489 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
1493 bool Outbound_Reply_Server(std::deque<std::string> ¶ms)
1495 if (params.size() < 4)
1497 std::string servername = params[0];
1498 std::string password = params[1];
1499 int hops = atoi(params[2].c_str());
1502 this->WriteLine("ERROR :Server too far away for authentication");
1505 std::string description = params[3];
1506 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1508 if ((x->Name == servername) && (x->RecvPass == password))
1510 TreeServer* CheckDupe = FindServer(servername);
1513 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1516 // Begin the sync here. this kickstarts the
1517 // other side, waiting in WAIT_AUTH_2 state,
1518 // into starting their burst, as it shows
1519 // that we're happy.
1520 this->LinkState = CONNECTED;
1521 // we should add the details of this server now
1522 // to the servers tree, as a child of the root
1524 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
1525 TreeRoot->AddChild(Node);
1526 params[3] = ":" + params[3];
1527 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
1528 this->bursting = true;
1529 this->DoBurst(Node);
1533 this->WriteLine("ERROR :Invalid credentials");
1537 bool Inbound_Server(std::deque<std::string> ¶ms)
1539 if (params.size() < 4)
1541 std::string servername = params[0];
1542 std::string password = params[1];
1543 int hops = atoi(params[2].c_str());
1546 this->WriteLine("ERROR :Server too far away for authentication");
1549 std::string description = params[3];
1550 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1552 if ((x->Name == servername) && (x->RecvPass == password))
1554 TreeServer* CheckDupe = FindServer(servername);
1557 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1560 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
1561 this->InboundServerName = servername;
1562 this->InboundDescription = description;
1563 // this is good. Send our details: Our server name and description and hopcount of 0,
1564 // along with the sendpass from this block.
1565 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
1566 // move to the next state, we are now waiting for THEM.
1567 this->LinkState = WAIT_AUTH_2;
1571 this->WriteLine("ERROR :Invalid credentials");
1575 void Split(std::string line, bool stripcolon, std::deque<std::string> &n)
1577 if (!strchr(line.c_str(),' '))
1582 std::stringstream s(line);
1583 std::string param = "";
1602 if ((param == ":") && (item > 0))
1625 bool ProcessLine(std::string line)
1627 char* l = (char*)line.c_str();
1628 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
1629 l[strlen(l)-1] = '\0';
1633 Srv->Log(DEBUG,"IN: '"+line+"'");
1634 std::deque<std::string> params;
1635 this->Split(line,true,params);
1636 std::string command = "";
1637 std::string prefix = "";
1638 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
1641 command = params[1];
1642 char* pref = (char*)prefix.c_str();
1650 command = params[0];
1654 switch (this->LinkState)
1659 // Waiting for SERVER command from remote server. Server initiating
1660 // the connection sends the first SERVER command, listening server
1661 // replies with theirs if its happy, then if the initiator is happy,
1662 // it starts to send its net sync, which starts the merge, otherwise
1663 // it sends an ERROR.
1664 if (command == "SERVER")
1666 return this->Inbound_Server(params);
1668 else if (command == "ERROR")
1670 return this->Error(params);
1674 // Waiting for start of other side's netmerge to say they liked our
1676 if (command == "SERVER")
1678 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1682 else if (command == "BURST")
1684 this->LinkState = CONNECTED;
1685 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
1686 TreeRoot->AddChild(Node);
1688 params.push_back(InboundServerName);
1689 params.push_back("*");
1690 params.push_back("1");
1691 params.push_back(":"+InboundDescription);
1692 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
1693 this->bursting = true;
1694 this->DoBurst(Node);
1696 else if (command == "ERROR")
1698 return this->Error(params);
1703 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
1707 if (command == "SERVER")
1709 // another server we connected to, which was in WAIT_AUTH_1 state,
1710 // has just sent us their credentials. If we get this far, theyre
1711 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1712 // if we're happy with this, we should send our netburst which
1713 // kickstarts the merge.
1714 return this->Outbound_Reply_Server(params);
1716 else if (command == "ERROR")
1718 return this->Error(params);
1722 // This is the 'authenticated' state, when all passwords
1723 // have been exchanged and anything past this point is taken
1728 std::string direction = prefix;
1729 userrec* t = Srv->FindNick(prefix);
1732 direction = t->server;
1734 TreeServer* route_back_again = BestRouteTo(direction);
1735 if ((!route_back_again) || (route_back_again->GetSocket() != this))
1737 if (route_back_again)
1739 WriteOpers("Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
1743 WriteOpers("Protocol violation: Invalid source '%s' in command '%s' from connection '%s'",direction.c_str(),line.c_str(),this->GetName().c_str());
1750 if (command == "SVSMODE")
1752 /* Services expects us to implement
1753 * SVSMODE. In inspircd its the same as
1758 std::string target = "";
1759 /* Yes, know, this is a mess. Its reasonably fast though as we're
1760 * working with std::string here.
1762 if ((command == "NICK") && (params.size() > 1))
1764 return this->IntroduceClient(prefix,params);
1766 else if (command == "FJOIN")
1768 return this->ForceJoin(prefix,params);
1770 else if (command == "SERVER")
1772 return this->RemoteServer(prefix,params);
1774 else if (command == "ERROR")
1776 return this->Error(params);
1778 else if (command == "OPERTYPE")
1780 return this->OperType(prefix,params);
1782 else if (command == "FMODE")
1784 return this->ForceMode(prefix,params);
1786 else if (command == "KILL")
1788 return this->RemoteKill(prefix,params);
1790 else if (command == "FTOPIC")
1792 return this->ForceTopic(prefix,params);
1794 else if (command == "REHASH")
1796 return this->RemoteRehash(prefix,params);
1798 else if (command == "METADATA")
1800 return this->MetaData(prefix,params);
1802 else if (command == "PING")
1804 return this->LocalPing(prefix,params);
1806 else if (command == "PONG")
1808 return this->LocalPong(prefix,params);
1810 else if (command == "VERSION")
1812 return this->ServerVersion(prefix,params);
1814 else if (command == "FHOST")
1816 return this->ChangeHost(prefix,params);
1818 else if (command == "FNAME")
1820 return this->ChangeName(prefix,params);
1822 else if (command == "ADDLINE")
1824 return this->AddLine(prefix,params);
1826 else if (command == "SVSNICK")
1830 prefix = this->GetName();
1832 return this->ForceNick(prefix,params);
1834 else if (command == "IDLE")
1836 return this->Whois(prefix,params);
1838 else if (command == "SVSJOIN")
1842 prefix = this->GetName();
1844 return this->ServiceJoin(prefix,params);
1846 else if (command == "SQUIT")
1848 if (params.size() == 2)
1850 this->Squit(FindServer(params[0]),params[1]);
1854 else if (command == "ENDBURST")
1856 this->bursting = false;
1861 // not a special inter-server command.
1862 // Emulate the actual user doing the command,
1863 // this saves us having a huge ugly parser.
1864 userrec* who = Srv->FindNick(prefix);
1865 std::string sourceserv = this->myhost;
1866 if (this->InboundServerName != "")
1868 sourceserv = this->InboundServerName;
1873 target = who->server;
1874 char* strparams[127];
1875 for (unsigned int q = 0; q < params.size(); q++)
1877 strparams[q] = (char*)params[q].c_str();
1879 Srv->CallCommandHandler(command, strparams, params.size(), who);
1883 // its not a user. Its either a server, or somethings screwed up.
1884 if (IsServer(prefix))
1886 target = Srv->GetServerName();
1890 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
1894 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1903 virtual std::string GetName()
1905 std::string sourceserv = this->myhost;
1906 if (this->InboundServerName != "")
1908 sourceserv = this->InboundServerName;
1913 virtual void OnTimeout()
1915 if (this->LinkState == CONNECTING)
1917 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
1921 virtual void OnClose()
1923 // Connection closed.
1924 // If the connection is fully up (state CONNECTED)
1925 // then propogate a netsplit to all peers.
1926 std::string quitserver = this->myhost;
1927 if (this->InboundServerName != "")
1929 quitserver = this->InboundServerName;
1931 TreeServer* s = FindServer(quitserver);
1934 Squit(s,"Remote host closed the connection");
1938 virtual int OnIncomingConnection(int newsock, char* ip)
1940 TreeSocket* s = new TreeSocket(newsock, ip);
1946 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
1948 for (unsigned int c = 0; c < list.size(); c++)
1950 if (list[c] == server)
1955 list.push_back(server);
1958 // returns a list of DIRECT servernames for a specific channel
1959 void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
1961 std::vector<char*> *ulist = c->GetUsers();
1962 unsigned int ucount = ulist->size();
1963 for (unsigned int i = 0; i < ucount; i++)
1965 char* o = (*ulist)[i];
1966 userrec* otheruser = (userrec*)o;
1967 if (otheruser->fd < 0)
1969 TreeServer* best = BestRouteTo(otheruser->server);
1971 AddThisServer(best,list);
1977 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, std::string command, std::deque<std::string> ¶ms)
1979 TreeServer* omitroute = BestRouteTo(omit);
1980 if ((command == "NOTICE") || (command == "PRIVMSG"))
1982 if ((params.size() >= 2) && (*(params[0].c_str()) != '$'))
1984 if (*(params[0].c_str()) != '#')
1986 // special routing for private messages/notices
1987 userrec* d = Srv->FindNick(params[0]);
1990 std::deque<std::string> par;
1991 par.push_back(params[0]);
1992 par.push_back(":"+params[1]);
1993 DoOneToOne(prefix,command,par,d->server);
1999 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
2000 chanrec* c = Srv->FindChannel(params[0]);
2003 std::deque<TreeServer*> list;
2004 GetListOfServersForChannel(c,list);
2005 log(DEBUG,"Got a list of %d servers",list.size());
2006 unsigned int lsize = list.size();
2007 for (unsigned int i = 0; i < lsize; i++)
2009 TreeSocket* Sock = list[i]->GetSocket();
2010 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
2012 log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
2013 Sock->WriteLine(data);
2021 unsigned int items = TreeRoot->ChildCount();
2022 for (unsigned int x = 0; x < items; x++)
2024 TreeServer* Route = TreeRoot->GetChild(x);
2025 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
2027 TreeSocket* Sock = Route->GetSocket();
2028 Sock->WriteLine(data);
2034 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string omit)
2036 TreeServer* omitroute = BestRouteTo(omit);
2037 std::string FullLine = ":" + prefix + " " + command;
2038 unsigned int words = params.size();
2039 for (unsigned int x = 0; x < words; x++)
2041 FullLine = FullLine + " " + params[x];
2043 unsigned int items = TreeRoot->ChildCount();
2044 for (unsigned int x = 0; x < items; x++)
2046 TreeServer* Route = TreeRoot->GetChild(x);
2047 // Send the line IF:
2048 // The route has a socket (its a direct connection)
2049 // The route isnt the one to be omitted
2050 // The route isnt the path to the one to be omitted
2051 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
2053 TreeSocket* Sock = Route->GetSocket();
2054 Sock->WriteLine(FullLine);
2060 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> ¶ms)
2062 std::string FullLine = ":" + prefix + " " + command;
2063 unsigned int words = params.size();
2064 for (unsigned int x = 0; x < words; x++)
2066 FullLine = FullLine + " " + params[x];
2068 unsigned int items = TreeRoot->ChildCount();
2069 for (unsigned int x = 0; x < items; x++)
2071 TreeServer* Route = TreeRoot->GetChild(x);
2072 if (Route->GetSocket())
2074 TreeSocket* Sock = Route->GetSocket();
2075 Sock->WriteLine(FullLine);
2081 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string target)
2083 TreeServer* Route = BestRouteTo(target);
2086 std::string FullLine = ":" + prefix + " " + command;
2087 unsigned int words = params.size();
2088 for (unsigned int x = 0; x < words; x++)
2090 FullLine = FullLine + " " + params[x];
2092 if (Route->GetSocket())
2094 TreeSocket* Sock = Route->GetSocket();
2095 Sock->WriteLine(FullLine);
2105 std::vector<TreeSocket*> Bindings;
2107 void ReadConfiguration(bool rebind)
2109 Conf = new ConfigReader;
2112 for (int j =0; j < Conf->Enumerate("bind"); j++)
2114 std::string Type = Conf->ReadValue("bind","type",j);
2115 std::string IP = Conf->ReadValue("bind","address",j);
2116 long Port = Conf->ReadInteger("bind","port",j,true);
2117 if (Type == "servers")
2123 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
2124 if (listener->GetState() == I_LISTENING)
2126 Srv->AddSocket(listener);
2127 Bindings.push_back(listener);
2131 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
2139 for (int j =0; j < Conf->Enumerate("link"); j++)
2142 L.Name = Conf->ReadValue("link","name",j);
2143 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
2144 L.Port = Conf->ReadInteger("link","port",j,true);
2145 L.SendPass = Conf->ReadValue("link","sendpass",j);
2146 L.RecvPass = Conf->ReadValue("link","recvpass",j);
2147 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
2148 L.NextConnectTime = time(NULL) + L.AutoConnect;
2149 LinkBlocks.push_back(L);
2150 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
2156 class ModuleSpanningTree : public Module
2158 std::vector<TreeSocket*> Bindings;
2164 ModuleSpanningTree(Server* Me)
2165 : Module::Module(Me)
2170 // Create the root of the tree
2171 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
2173 ReadConfiguration(true);
2176 void ShowLinks(TreeServer* Current, userrec* user, int hops)
2178 std::string Parent = TreeRoot->GetName();
2179 if (Current->GetParent())
2181 Parent = Current->GetParent()->GetName();
2183 for (unsigned int q = 0; q < Current->ChildCount(); q++)
2185 ShowLinks(Current->GetChild(q),user,hops+1);
2187 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
2190 int CountLocalServs()
2192 return TreeRoot->ChildCount();
2197 return serverlist.size();
2200 void HandleLinks(char** parameters, int pcnt, userrec* user)
2202 ShowLinks(TreeRoot,user,0);
2203 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
2207 void HandleLusers(char** parameters, int pcnt, userrec* user)
2209 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),this->CountServs());
2210 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
2211 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
2212 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
2213 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
2217 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
2219 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
2223 for (int t = 0; t < depth; t++)
2225 matrix[line][t] = ' ';
2227 strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
2229 for (unsigned int q = 0; q < Current->ChildCount(); q++)
2231 ShowMap(Current->GetChild(q),user,depth+2,matrix);
2236 // Ok, prepare to be confused.
2237 // After much mulling over how to approach this, it struck me that
2238 // the 'usual' way of doing a /MAP isnt the best way. Instead of
2239 // keeping track of a ton of ascii characters, and line by line
2240 // under recursion working out where to place them using multiplications
2241 // and divisons, we instead render the map onto a backplane of characters
2242 // (a character matrix), then draw the branches as a series of "L" shapes
2243 // from the nodes. This is not only friendlier on CPU it uses less stack.
2245 void HandleMap(char** parameters, int pcnt, userrec* user)
2247 // This array represents a virtual screen which we will
2248 // "scratch" draw to, as the console device of an irc
2249 // client does not provide for a proper terminal.
2250 char matrix[128][80];
2251 for (unsigned int t = 0; t < 128; t++)
2253 matrix[t][0] = '\0';
2256 // The only recursive bit is called here.
2257 ShowMap(TreeRoot,user,0,matrix);
2258 // Process each line one by one. The algorithm has a limit of
2259 // 128 servers (which is far more than a spanning tree should have
2260 // anyway, so we're ok). This limit can be raised simply by making
2261 // the character matrix deeper, 128 rows taking 10k of memory.
2262 for (int l = 1; l < line; l++)
2264 // scan across the line looking for the start of the
2265 // servername (the recursive part of the algorithm has placed
2266 // the servers at indented positions depending on what they
2268 int first_nonspace = 0;
2269 while (matrix[l][first_nonspace] == ' ')
2274 // Draw the `- (corner) section: this may be overwritten by
2275 // another L shape passing along the same vertical pane, becoming
2276 // a |- (branch) section instead.
2277 matrix[l][first_nonspace] = '-';
2278 matrix[l][first_nonspace-1] = '`';
2280 // Draw upwards until we hit the parent server, causing possibly
2281 // other corners (`-) to become branches (|-)
2282 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
2284 matrix[l2][first_nonspace-1] = '|';
2288 // dump the whole lot to the user. This is the easy bit, honest.
2289 for (int t = 0; t < line; t++)
2291 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
2293 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
2297 int HandleSquit(char** parameters, int pcnt, userrec* user)
2299 TreeServer* s = FindServerMask(parameters[0]);
2302 TreeSocket* sock = s->GetSocket();
2305 WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
2306 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
2311 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
2316 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
2321 int HandleRemoteWhois(char** parameters, int pcnt, userrec* user)
2323 if ((user->fd > -1) && (pcnt > 1))
2325 userrec* remote = Srv->FindNick(parameters[1]);
2326 if ((remote) && (remote->fd < 0))
2328 std::deque<std::string> params;
2329 params.push_back(parameters[1]);
2330 DoOneToOne(user->nick,"IDLE",params,remote->server);
2335 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
2336 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
2343 void DoPingChecks(time_t curtime)
2345 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
2347 TreeServer* serv = TreeRoot->GetChild(j);
2348 TreeSocket* sock = serv->GetSocket();
2351 if (curtime >= serv->NextPingTime())
2353 if (serv->AnsweredLastPing())
2355 sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
2356 serv->SetNextPingTime(curtime + 60);
2360 // they didnt answer, boot them
2361 WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
2362 sock->Squit(serv,"Ping timeout");
2371 void AutoConnectServers(time_t curtime)
2373 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2375 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
2377 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
2378 x->NextConnectTime = curtime + x->AutoConnect;
2379 TreeServer* CheckDupe = FindServer(x->Name);
2382 // an autoconnected server is not connected. Check if its time to connect it
2383 WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
2384 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2385 Srv->AddSocket(newsocket);
2391 int HandleVersion(char** parameters, int pcnt, userrec* user)
2393 // we've already checked if pcnt > 0, so this is safe
2394 TreeServer* found = FindServerMask(parameters[0]);
2397 std::string Version = found->GetVersion();
2398 WriteServ(user->fd,"351 %s :%s",user->nick,Version.c_str());
2402 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
2407 int HandleConnect(char** parameters, int pcnt, userrec* user)
2409 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2411 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
2413 TreeServer* CheckDupe = FindServer(x->Name);
2416 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);
2417 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2418 Srv->AddSocket(newsocket);
2423 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());
2428 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
2432 virtual bool HandleStats(char ** parameters, int pcnt, userrec* user)
2434 if (*parameters[0] == 'c')
2436 for (unsigned int i = 0; i < LinkBlocks.size(); i++)
2438 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);
2439 WriteServ(user->fd,"244 %s H * * %s",user->nick,LinkBlocks[i].Name.c_str());
2441 WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
2442 WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
2448 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
2450 if (command == "CONNECT")
2452 return this->HandleConnect(parameters,pcnt,user);
2454 else if (command == "SQUIT")
2456 return this->HandleSquit(parameters,pcnt,user);
2458 else if (command == "STATS")
2460 return this->HandleStats(parameters,pcnt,user);
2462 else if (command == "MAP")
2464 this->HandleMap(parameters,pcnt,user);
2467 else if (command == "LUSERS")
2469 this->HandleLusers(parameters,pcnt,user);
2472 else if (command == "LINKS")
2474 this->HandleLinks(parameters,pcnt,user);
2477 else if (command == "WHOIS")
2482 return this->HandleRemoteWhois(parameters,pcnt,user);
2485 else if ((command == "VERSION") && (pcnt > 0))
2487 this->HandleVersion(parameters,pcnt,user);
2490 else if (Srv->IsValidModuleCommand(command, pcnt, user))
2492 // this bit of code cleverly routes all module commands
2493 // to all remote severs *automatically* so that modules
2494 // can just handle commands locally, without having
2495 // to have any special provision in place for remote
2496 // commands and linking protocols.
2497 std::deque<std::string> params;
2499 for (int j = 0; j < pcnt; j++)
2501 if (strchr(parameters[j],' '))
2503 params.push_back(":" + std::string(parameters[j]));
2507 params.push_back(std::string(parameters[j]));
2510 DoOneToMany(user->nick,command,params);
2515 virtual void OnGetServerDescription(std::string servername,std::string &description)
2517 TreeServer* s = FindServer(servername);
2520 description = s->GetDesc();
2524 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
2526 if (source->fd > -1)
2528 std::deque<std::string> params;
2529 params.push_back(dest->nick);
2530 params.push_back(channel->name);
2531 DoOneToMany(source->nick,"INVITE",params);
2535 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
2537 std::deque<std::string> params;
2538 params.push_back(chan->name);
2539 params.push_back(":"+topic);
2540 DoOneToMany(user->nick,"TOPIC",params);
2543 virtual void OnWallops(userrec* user, std::string text)
2547 std::deque<std::string> params;
2548 params.push_back(":"+text);
2549 DoOneToMany(user->nick,"WALLOPS",params);
2553 virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
2555 if (target_type == TYPE_USER)
2557 userrec* d = (userrec*)dest;
2558 if ((d->fd < 0) && (user->fd > -1))
2560 std::deque<std::string> params;
2562 params.push_back(d->nick);
2563 params.push_back(":"+text);
2564 DoOneToOne(user->nick,"NOTICE",params,d->server);
2571 chanrec *c = (chanrec*)dest;
2572 std::deque<TreeServer*> list;
2573 GetListOfServersForChannel(c,list);
2574 unsigned int ucount = list.size();
2575 for (unsigned int i = 0; i < ucount; i++)
2577 TreeSocket* Sock = list[i]->GetSocket();
2579 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+std::string(c->name)+" :"+text);
2585 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
2587 if (target_type == TYPE_USER)
2589 // route private messages which are targetted at clients only to the server
2590 // which needs to receive them
2591 userrec* d = (userrec*)dest;
2592 if ((d->fd < 0) && (user->fd > -1))
2594 std::deque<std::string> params;
2596 params.push_back(d->nick);
2597 params.push_back(":"+text);
2598 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
2605 chanrec *c = (chanrec*)dest;
2606 std::deque<TreeServer*> list;
2607 GetListOfServersForChannel(c,list);
2608 unsigned int ucount = list.size();
2609 for (unsigned int i = 0; i < ucount; i++)
2611 TreeSocket* Sock = list[i]->GetSocket();
2613 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+std::string(c->name)+" :"+text);
2619 virtual void OnBackgroundTimer(time_t curtime)
2621 AutoConnectServers(curtime);
2622 DoPingChecks(curtime);
2625 virtual void OnUserJoin(userrec* user, chanrec* channel)
2627 // Only do this for local users
2630 std::deque<std::string> params;
2632 params.push_back(channel->name);
2635 // if the channel has a key, force the join by emulating the key.
2636 params.push_back(channel->key);
2638 if (channel->GetUserCounter() > 1)
2640 // not the first in the channel
2641 DoOneToMany(user->nick,"JOIN",params);
2645 // first in the channel, set up their permissions
2646 // and the channel TS with FJOIN.
2648 snprintf(ts,24,"%lu",(unsigned long)channel->age);
2650 params.push_back(channel->name);
2651 params.push_back(ts);
2652 params.push_back("@"+std::string(user->nick));
2653 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
2658 virtual void OnChangeHost(userrec* user, std::string newhost)
2660 // only occurs for local clients
2661 if (user->registered != 7)
2663 std::deque<std::string> params;
2664 params.push_back(newhost);
2665 DoOneToMany(user->nick,"FHOST",params);
2668 virtual void OnChangeName(userrec* user, std::string gecos)
2670 // only occurs for local clients
2671 if (user->registered != 7)
2673 std::deque<std::string> params;
2674 params.push_back(gecos);
2675 DoOneToMany(user->nick,"FNAME",params);
2678 virtual void OnUserPart(userrec* user, chanrec* channel)
2682 std::deque<std::string> params;
2683 params.push_back(channel->name);
2684 DoOneToMany(user->nick,"PART",params);
2688 virtual void OnUserConnect(userrec* user)
2690 char agestr[MAXBUF];
2693 std::deque<std::string> params;
2694 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
2695 params.push_back(agestr);
2696 params.push_back(user->nick);
2697 params.push_back(user->host);
2698 params.push_back(user->dhost);
2699 params.push_back(user->ident);
2700 params.push_back("+"+std::string(user->modes));
2701 params.push_back(user->ip);
2702 params.push_back(":"+std::string(user->fullname));
2703 DoOneToMany(Srv->GetServerName(),"NICK",params);
2707 virtual void OnUserQuit(userrec* user, std::string reason)
2709 if ((user->fd > -1) && (user->registered == 7))
2711 std::deque<std::string> params;
2712 params.push_back(":"+reason);
2713 DoOneToMany(user->nick,"QUIT",params);
2717 virtual void OnUserPostNick(userrec* user, std::string oldnick)
2721 std::deque<std::string> params;
2722 params.push_back(user->nick);
2723 DoOneToMany(oldnick,"NICK",params);
2727 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
2729 if (source->fd > -1)
2731 std::deque<std::string> params;
2732 params.push_back(chan->name);
2733 params.push_back(user->nick);
2734 params.push_back(":"+reason);
2735 DoOneToMany(source->nick,"KICK",params);
2739 virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
2741 std::deque<std::string> params;
2742 params.push_back(dest->nick);
2743 params.push_back(":"+reason);
2744 DoOneToMany(source->nick,"KILL",params);
2747 virtual void OnRehash(std::string parameter)
2749 if (parameter != "")
2751 std::deque<std::string> params;
2752 params.push_back(parameter);
2753 DoOneToMany(Srv->GetServerName(),"REHASH",params);
2755 if (Srv->MatchText(Srv->GetServerName(),parameter))
2757 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
2758 Srv->RehashServer();
2761 ReadConfiguration(false);
2764 // note: the protocol does not allow direct umode +o except
2765 // via NICK with 8 params. sending OPERTYPE infers +o modechange
2767 virtual void OnOper(userrec* user, std::string opertype)
2771 std::deque<std::string> params;
2772 params.push_back(opertype);
2773 DoOneToMany(user->nick,"OPERTYPE",params);
2777 void OnLine(userrec* source, std::string host, bool adding, char linetype, long duration, std::string reason)
2779 if (source->fd > -1)
2782 snprintf(type,8,"%cLINE",linetype);
2783 std::string stype = type;
2786 char sduration[MAXBUF];
2787 snprintf(sduration,MAXBUF,"%ld",duration);
2788 std::deque<std::string> params;
2789 params.push_back(host);
2790 params.push_back(sduration);
2791 params.push_back(":"+reason);
2792 DoOneToMany(source->nick,stype,params);
2796 std::deque<std::string> params;
2797 params.push_back(host);
2798 DoOneToMany(source->nick,stype,params);
2803 virtual void OnAddGLine(long duration, userrec* source, std::string reason, std::string hostmask)
2805 OnLine(source,hostmask,true,'G',duration,reason);
2808 virtual void OnAddZLine(long duration, userrec* source, std::string reason, std::string ipmask)
2810 OnLine(source,ipmask,true,'Z',duration,reason);
2813 virtual void OnAddQLine(long duration, userrec* source, std::string reason, std::string nickmask)
2815 OnLine(source,nickmask,true,'Q',duration,reason);
2818 virtual void OnAddELine(long duration, userrec* source, std::string reason, std::string hostmask)
2820 OnLine(source,hostmask,true,'E',duration,reason);
2823 virtual void OnDelGLine(userrec* source, std::string hostmask)
2825 OnLine(source,hostmask,false,'G',0,"");
2828 virtual void OnDelZLine(userrec* source, std::string ipmask)
2830 OnLine(source,ipmask,false,'Z',0,"");
2833 virtual void OnDelQLine(userrec* source, std::string nickmask)
2835 OnLine(source,nickmask,false,'Q',0,"");
2838 virtual void OnDelELine(userrec* source, std::string hostmask)
2840 OnLine(source,hostmask,false,'E',0,"");
2843 virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
2845 if ((user->fd > -1) && (user->registered == 7))
2847 if (target_type == TYPE_USER)
2849 userrec* u = (userrec*)dest;
2850 std::deque<std::string> params;
2851 params.push_back(u->nick);
2852 params.push_back(text);
2853 DoOneToMany(user->nick,"MODE",params);
2857 chanrec* c = (chanrec*)dest;
2858 std::deque<std::string> params;
2859 params.push_back(c->name);
2860 params.push_back(text);
2861 DoOneToMany(user->nick,"MODE",params);
2866 virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
2868 TreeSocket* s = (TreeSocket*)opaque;
2871 if (target_type == TYPE_USER)
2873 userrec* u = (userrec*)target;
2874 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
2878 chanrec* c = (chanrec*)target;
2879 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
2884 virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, std::string extname, std::string extdata)
2886 TreeSocket* s = (TreeSocket*)opaque;
2889 if (target_type == TYPE_USER)
2891 userrec* u = (userrec*)target;
2892 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+u->nick+" "+extname+" :"+extdata);
2896 chanrec* c = (chanrec*)target;
2897 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+c->name+" "+extname+" :"+extdata);
2902 virtual ~ModuleSpanningTree()
2906 virtual Version GetVersion()
2908 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
2913 class ModuleSpanningTreeFactory : public ModuleFactory
2916 ModuleSpanningTreeFactory()
2920 ~ModuleSpanningTreeFactory()
2924 virtual Module * CreateModule(Server* Me)
2926 TreeProtocolModule = new ModuleSpanningTree(Me);
2927 return TreeProtocolModule;
2933 extern "C" void * init_module( void )
2935 return new ModuleSpanningTreeFactory;