1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * Inspire is copyright (C) 2002-2005 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
17 /* $ModDesc: Povides a spanning tree server link protocol */
25 #include "inspircd_config.h"
27 #include <ext/hash_map>
35 #include "helperfuncs.h"
37 #include "inspstring.h"
43 #define nspace __gnu_cxx
49 * The server list in InspIRCd is maintained as two structures
50 * which hold the data in different ways. Most of the time, we
51 * want to very quicky obtain three pieces of information:
53 * (1) The information on a server
54 * (2) The information on the server we must send data through
55 * to actually REACH the server we're after
56 * (3) Potentially, the child/parent objects of this server
58 * The InspIRCd spanning protocol provides easy access to these
59 * by storing the data firstly in a recursive structure, where
60 * each item references its parent item, and a dynamic list
61 * of child items, and another structure which stores the items
62 * hashed, linearly. This means that if we want to find a server
63 * by name quickly, we can look it up in the hash, avoiding
64 * any O(n) lookups. If however, during a split or sync, we want
65 * to apply an operation to a server, and any of its child objects
66 * we can resort to recursion to walk the tree structure.
69 class ModuleSpanningTree;
70 static ModuleSpanningTree* TreeProtocolModule;
72 extern std::vector<Module*> modules;
73 extern std::vector<ircd_module*> factory;
76 /* Any socket can have one of five states at any one time.
77 * The LISTENER state indicates a socket which is listening
78 * for connections. It cannot receive data itself, only incoming
80 * The CONNECTING state indicates an outbound socket which is
81 * waiting to be writeable.
82 * The WAIT_AUTH_1 state indicates the socket is outbound and
83 * has successfully connected, but has not yet sent and received
85 * The WAIT_AUTH_2 state indicates that the socket is inbound
86 * (allocated by a LISTENER) but has not yet sent and received
88 * The CONNECTED state represents a fully authorized, fully
91 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
93 /* We need to import these from the core for use in netbursts */
94 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
95 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;
96 extern user_hash clientlist;
97 extern chan_hash chanlist;
99 /* Foward declarations */
103 /* This variable represents the root of the server tree
104 * (for all intents and purposes, it's us)
106 TreeServer *TreeRoot;
108 /* This hash_map holds the hash equivalent of the server
109 * tree, used for rapid linear lookups.
111 typedef nspace::hash_map<std::string, TreeServer*> server_hash;
112 server_hash serverlist;
114 /* More forward declarations */
115 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target);
116 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit);
117 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params);
118 bool DoOneToAllButSenderRaw(std::string data,std::string omit, std::string prefix,std::string command,std::deque<std::string> params);
119 void ReadConfiguration(bool rebind);
121 /* Imported from xline.cpp for use during netburst */
122 extern std::vector<KLine> klines;
123 extern std::vector<GLine> glines;
124 extern std::vector<ZLine> zlines;
125 extern std::vector<QLine> qlines;
126 extern std::vector<ELine> elines;
129 /* Each server in the tree is represented by one class of
130 * type TreeServer. A locally connected TreeServer can
131 * have a class of type TreeSocket associated with it, for
132 * remote servers, the TreeSocket entry will be NULL.
133 * Each server also maintains a pointer to its parent
134 * (NULL if this server is ours, at the top of the tree)
135 * and a pointer to its "Route" (see the comments in the
136 * constructors below), and also a dynamic list of pointers
137 * to its children which can be iterated recursively
138 * if required. Creating or deleting objects of type
139 * TreeServer automatically maintains the hash_map of
140 * TreeServer items, deleting and inserting them as they
141 * are created and destroyed.
146 TreeServer* Parent; /* Parent entry */
147 TreeServer* Route; /* Route entry */
148 std::vector<TreeServer*> Children; /* List of child objects */
149 std::string ServerName; /* Server's name */
150 std::string ServerDesc; /* Server's description */
151 std::string VersionString; /* Version string or empty string */
152 int UserCount; /* Not used in this version */
153 int OperCount; /* Not used in this version */
154 TreeSocket* Socket; /* For directly connected servers this points at the socket object */
155 time_t NextPing; /* After this time, the server should be PINGed*/
156 bool LastPingWasGood; /* True if the server responded to the last PING with a PONG */
160 /* We don't use this constructor. Its a dummy, and won't cause any insertion
161 * of the TreeServer into the hash_map. See below for the two we DO use.
169 UserCount = OperCount = 0;
170 VersionString = GetVersionString();
173 /* We use this constructor only to create the 'root' item, TreeRoot, which
174 * represents our own server. Therefore, it has no route, no parent, and
175 * no socket associated with it. Its version string is our own local version.
177 TreeServer(std::string Name, std::string Desc) : ServerName(Name), ServerDesc(Desc)
181 UserCount = OperCount = 0;
182 VersionString = GetVersionString();
187 /* When we create a new server, we call this constructor to initialize it.
188 * This constructor initializes the server's Route and Parent, and sets up
189 * its ping counters so that it will be pinged one minute from now.
191 TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name), ServerDesc(Desc), Socket(Sock)
194 UserCount = OperCount = 0;
195 this->SetNextPingTime(time(NULL) + 60);
198 /* find the 'route' for this server (e.g. the one directly connected
199 * to the local server, which we can use to reach it)
201 * In the following example, consider we have just added a TreeServer
202 * class for server G on our network, of which we are server A.
203 * To route traffic to G (marked with a *) we must send the data to
204 * B (marked with a +) so this algorithm initializes the 'Route'
205 * value to point at whichever server traffic must be routed through
206 * to get here. If we were to try this algorithm with server B,
207 * the Route pointer would point at its own object ('this').
217 * We only run this algorithm when a server is created, as
218 * the routes remain constant while ever the server exists, and
219 * do not need to be re-calculated.
223 if (Route == TreeRoot)
229 while (this->Route->GetParent() != TreeRoot)
231 this->Route = Route->GetParent();
235 /* Because recursive code is slow and takes a lot of resources,
236 * we store two representations of the server tree. The first
237 * is a recursive structure where each server references its
238 * children and its parent, which is used for netbursts and
239 * netsplits to dump the whole dataset to the other server,
240 * and the second is used for very fast lookups when routing
241 * messages and is instead a hash_map, where each item can
242 * be referenced by its server name. The AddHashEntry()
243 * call below automatically inserts each TreeServer class
244 * into the hash_map as it is created. There is a similar
245 * maintainance call in the destructor to tidy up deleted
249 this->AddHashEntry();
252 /* This method is used to add the structure to the
253 * hash_map for linear searches. It is only called
254 * by the constructors.
258 server_hash::iterator iter;
259 iter = serverlist.find(this->ServerName);
260 if (iter == serverlist.end())
261 serverlist[this->ServerName] = this;
264 /* This method removes the reference to this object
265 * from the hash_map which is used for linear searches.
266 * It is only called by the default destructor.
270 server_hash::iterator iter;
271 iter = serverlist.find(this->ServerName);
272 if (iter != serverlist.end())
273 serverlist.erase(iter);
276 /* These accessors etc should be pretty self-
280 TreeServer* GetRoute()
285 std::string GetName()
287 return this->ServerName;
290 std::string GetDesc()
292 return this->ServerDesc;
295 std::string GetVersion()
297 return this->VersionString;
300 void SetNextPingTime(time_t t)
303 LastPingWasGood = false;
306 time_t NextPingTime()
308 return this->NextPing;
311 bool AnsweredLastPing()
313 return LastPingWasGood;
318 LastPingWasGood = true;
323 return this->UserCount;
328 return this->OperCount;
331 TreeSocket* GetSocket()
336 TreeServer* GetParent()
341 void SetVersion(std::string Version)
343 VersionString = Version;
346 unsigned int ChildCount()
348 return Children.size();
351 TreeServer* GetChild(unsigned int n)
353 if (n < Children.size())
355 /* Make sure they cant request
356 * an out-of-range object. After
357 * all we know what these programmer
358 * types are like *grin*.
368 void AddChild(TreeServer* Child)
370 Children.push_back(Child);
373 bool DelChild(TreeServer* Child)
375 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
386 /* Removes child nodes of this node, and of that node, etc etc.
387 * This is used during netsplits to automatically tidy up the
388 * server tree. It is slow, we don't use it for much else.
392 bool stillchildren = true;
393 while (stillchildren)
395 stillchildren = false;
396 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
398 TreeServer* s = (TreeServer*)*a;
402 stillchildren = true;
411 /* We'd better tidy up after ourselves, eh? */
412 this->DelHashEntry();
416 /* The Link class might as well be a struct,
417 * but this is C++ and we don't believe in structs (!).
418 * It holds the entire information of one <link>
419 * tag from the main config file. We maintain a list
420 * of them, and populate the list on rehash/load.
429 std::string SendPass;
430 std::string RecvPass;
431 unsigned long AutoConnect;
432 time_t NextConnectTime;
435 /* The usual stuff for inspircd modules,
436 * plus the vector of Link classes which we
437 * use to store the <link> tags from the config
442 std::vector<Link> LinkBlocks;
444 /* Yay for fast searches!
445 * This is hundreds of times faster than recursion
446 * or even scanning a linked list, especially when
447 * there are more than a few servers to deal with.
450 TreeServer* FindServer(std::string ServerName)
452 server_hash::iterator iter;
453 iter = serverlist.find(ServerName);
454 if (iter != serverlist.end())
464 /* Returns the locally connected server we must route a
465 * message through to reach server 'ServerName'. This
466 * only applies to one-to-one and not one-to-many routing.
467 * See the comments for the constructor of TreeServer
470 TreeServer* BestRouteTo(std::string ServerName)
472 if (ServerName.c_str() == TreeRoot->GetName())
474 TreeServer* Found = FindServer(ServerName);
477 return Found->GetRoute();
485 /* Find the first server matching a given glob mask.
486 * Theres no find-using-glob method of hash_map [awwww :-(]
487 * so instead, we iterate over the list using an iterator
488 * and match each one until we get a hit. Yes its slow,
491 TreeServer* FindServerMask(std::string ServerName)
493 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
495 if (Srv->MatchText(i->first,ServerName))
501 /* A convenient wrapper that returns true if a server exists */
502 bool IsServer(std::string ServerName)
504 return (FindServer(ServerName) != NULL);
507 /* Every SERVER connection inbound or outbound is represented by
508 * an object of type TreeSocket.
509 * TreeSockets, being inherited from InspSocket, can be tied into
510 * the core socket engine, and we cn therefore receive activity events
511 * for them, just like activex objects on speed. (yes really, that
512 * is a technical term!) Each of these which relates to a locally
513 * connected server is assocated with it, by hooking it onto a
514 * TreeSocket class using its constructor. In this way, we can
515 * maintain a list of servers, some of which are directly connected,
516 * some of which are not.
519 class TreeSocket : public InspSocket
522 std::string in_buffer;
523 ServerState LinkState;
524 std::string InboundServerName;
525 std::string InboundDescription;
527 int num_lost_servers;
529 bool LastPingWasGood;
533 /* Because most of the I/O gubbins are encapsulated within
534 * InspSocket, we just call the superclass constructor for
535 * most of the action, and append a few of our own values
538 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
539 : InspSocket(host, port, listening, maxtime)
542 this->LinkState = LISTENER;
545 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
546 : InspSocket(host, port, listening, maxtime)
549 this->LinkState = CONNECTING;
552 /* When a listening socket gives us a new file descriptor,
553 * we must associate it with a socket without creating a new
554 * connection. This constructor is used for this purpose.
556 TreeSocket(int newfd, char* ip)
557 : InspSocket(newfd, ip)
559 this->LinkState = WAIT_AUTH_1;
562 /* When an outbound connection finishes connecting, we receive
563 * this event, and must send our SERVER string to the other
564 * side. If the other side is happy, as outlined in the server
565 * to server docs on the inspircd.org site, the other side
566 * will then send back its own server string.
568 virtual bool OnConnected()
570 if (this->LinkState == CONNECTING)
572 Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
573 /* we do not need to change state here. */
574 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
576 if (x->Name == this->myhost)
578 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
579 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
584 /* There is a (remote) chance that between the /CONNECT and the connection
585 * being accepted, some muppet has removed the <link> block and rehashed.
586 * If that happens the connection hangs here until it's closed. Unlikely
587 * and rather harmless.
592 virtual void OnError(InspSocketError e)
594 /* We don't handle this method, because all our
595 * dirty work is done in OnClose() (see below)
596 * which is still called on error conditions too.
600 virtual int OnDisconnect()
602 /* For the same reason as above, we don't
603 * handle OnDisconnect()
608 /* Recursively send the server tree with distances as hops.
609 * This is used during network burst to inform the other server
610 * (and any of ITS servers too) of what servers we know about.
611 * If at any point any of these servers already exist on the other
612 * end, our connection may be terminated. The hopcounts given
613 * by this function are relative, this doesn't matter so long as
614 * they are all >1, as all the remote servers re-calculate them
615 * to be relative too, with themselves as hop 0.
617 void SendServers(TreeServer* Current, TreeServer* s, int hops)
620 for (unsigned int q = 0; q < Current->ChildCount(); q++)
622 TreeServer* recursive_server = Current->GetChild(q);
623 if (recursive_server != s)
625 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
626 this->WriteLine(command);
627 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
628 /* down to next level */
629 this->SendServers(recursive_server, s, hops+1);
634 /* This function forces this server to quit, removing this server
635 * and any users on it (and servers and users below that, etc etc).
636 * It's very slow and pretty clunky, but luckily unless your network
637 * is having a REAL bad hair day, this function shouldnt be called
638 * too many times a month ;-)
640 void SquitServer(TreeServer* Current)
642 /* recursively squit the servers attached to 'Current'.
643 * We're going backwards so we don't remove users
644 * while we still need them ;)
646 for (unsigned int q = 0; q < Current->ChildCount(); q++)
648 TreeServer* recursive_server = Current->GetChild(q);
649 this->SquitServer(recursive_server);
651 /* Now we've whacked the kids, whack self */
653 bool quittingpeople = true;
654 while (quittingpeople)
656 /* Yup i know, "ew". We cant continue to loop through the
657 * iterator if we modify it, so whenever we modify it with a
658 * QUIT we have to start alllll over again. If anyone knows
659 * a better faster way of *safely* doing this, please let me
662 quittingpeople = false;
663 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
665 if (!strcasecmp(u->second->server,Current->GetName().c_str()))
667 Srv->QuitUser(u->second,Current->GetName()+" "+std::string(Srv->GetServerName()));
669 quittingpeople = true;
676 /* This is a wrapper function for SquitServer above, which
677 * does some validation first and passes on the SQUIT to all
678 * other remaining servers.
680 void Squit(TreeServer* Current,std::string reason)
684 std::deque<std::string> params;
685 params.push_back(Current->GetName());
686 params.push_back(":"+reason);
687 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
688 if (Current->GetParent() == TreeRoot)
690 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
694 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
696 num_lost_servers = 0;
698 SquitServer(Current);
700 Current->GetParent()->DelChild(Current);
702 WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
706 log(DEFAULT,"Squit from unknown server");
711 bool ForceMode(std::string source, std::deque<std::string> params)
713 userrec* who = new userrec;
714 who->fd = FD_MAGIC_NUMBER;
715 if (params.size() < 2)
718 for (unsigned int q = 0; q < params.size(); q++)
720 modelist[q] = (char*)params[q].c_str();
722 Srv->SendMode(modelist,params.size(),who);
723 DoOneToAllButSender(source,"FMODE",params,source);
729 bool ForceTopic(std::string source, std::deque<std::string> params)
731 if (params.size() != 4)
733 std::string channel = params[0];
734 time_t ts = atoi(params[1].c_str());
735 std::string setby = params[2];
736 std::string topic = params[3];
738 chanrec* c = Srv->FindChannel(channel);
741 if ((ts >= c->topicset) || (!*c->topic))
743 std::string oldtopic = c->topic;
744 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
745 strlcpy(c->setby,setby.c_str(),NICKMAX);
747 /* if the topic text is the same as the current topic,
748 * dont bother to send the TOPIC command out, just silently
749 * update the set time and set nick.
751 if (oldtopic != topic)
752 WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
757 /* all done, send it on its way */
758 params[3] = ":" + params[3];
759 DoOneToAllButSender(source,"FTOPIC",params,source);
764 /* FJOIN, similar to unreal SJOIN */
765 bool ForceJoin(std::string source, std::deque<std::string> params)
767 if (params.size() < 3)
771 char modestring[MAXBUF];
772 char* mode_users[127];
773 mode_users[0] = first;
774 mode_users[1] = modestring;
775 strcpy(mode_users[1],"+");
776 unsigned int modectr = 2;
779 std::string channel = params[0];
780 time_t TS = atoi(params[1].c_str());
783 chanrec* chan = Srv->FindChannel(channel);
788 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
790 /* default is a high value, which if we dont have this
791 * channel will let the other side apply their modes.
793 time_t ourTS = time(NULL)+600;
794 chanrec* us = Srv->FindChannel(channel);
800 log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
802 /* do this first, so our mode reversals are correctly received by other servers
803 * if there is a TS collision.
805 DoOneToAllButSender(source,"FJOIN",params,source);
807 for (unsigned int usernum = 2; usernum < params.size(); usernum++)
809 /* process one channel at a time, applying modes. */
810 char* usr = (char*)params[usernum].c_str();
811 char permissions = *usr;
816 mode_users[modectr++] = usr;
817 strlcat(modestring,"o",MAXBUF);
821 mode_users[modectr++] = usr;
822 strlcat(modestring,"h",MAXBUF);
826 mode_users[modectr++] = usr;
827 strlcat(modestring,"v",MAXBUF);
830 who = Srv->FindNick(usr);
833 Srv->JoinUserToChannel(who,channel,key);
834 if (modectr >= (MAXMODES-1))
836 /* theres a mode for this user. push them onto the mode queue, and flush it
837 * if there are more than MAXMODES to go.
841 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
842 Srv->SendMode(mode_users,modectr,who);
846 log(DEBUG,"Their channel newer than ours, bouncing their modes");
848 std::deque<std::string> params;
849 /* modes are now being UNSET... */
850 *mode_users[1] = '-';
851 for (unsigned int x = 0; x < modectr; x++)
853 params.push_back(mode_users[x]);
855 // tell everyone to bounce the modes. bad modes, bad!
856 DoOneToMany(Srv->GetServerName(),"FMODE",params);
858 strcpy(mode_users[1],"+");
863 /* there werent enough modes built up to flush it during FJOIN,
864 * or, there are a number left over. flush them out.
866 if ((modectr > 2) && (who))
870 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
871 Srv->SendMode(mode_users,modectr,who);
875 log(DEBUG,"Their channel newer than ours, bouncing their modes");
876 std::deque<std::string> params;
877 *mode_users[1] = '-';
878 for (unsigned int x = 0; x < modectr; x++)
880 params.push_back(mode_users[x]);
882 DoOneToMany(Srv->GetServerName(),"FMODE",params);
889 bool IntroduceClient(std::string source, std::deque<std::string> params)
891 if (params.size() < 8)
893 // NICK age nick host dhost ident +modes ip :gecos
895 std::string nick = params[1];
896 std::string host = params[2];
897 std::string dhost = params[3];
898 std::string ident = params[4];
899 time_t age = atoi(params[0].c_str());
900 std::string modes = params[5];
901 while (*(modes.c_str()) == '+')
903 char* m = (char*)modes.c_str();
907 std::string ip = params[6];
908 std::string gecos = params[7];
909 char* tempnick = (char*)nick.c_str();
910 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
912 user_hash::iterator iter;
913 iter = clientlist.find(tempnick);
914 if (iter != clientlist.end())
917 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);
918 this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
922 clientlist[tempnick] = new userrec();
923 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
924 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
925 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
926 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
927 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
928 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
929 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
930 clientlist[tempnick]->registered = 7;
931 clientlist[tempnick]->signon = age;
932 strlcpy(clientlist[tempnick]->modes, modes.c_str(),53);
933 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
934 for (int i = 0; i < MAXCHANS; i++)
936 clientlist[tempnick]->chans[i].channel = NULL;
937 clientlist[tempnick]->chans[i].uc_modes = 0;
939 params[7] = ":" + params[7];
940 DoOneToAllButSender(source,"NICK",params,source);
944 /* Send one or more FJOINs for a channel of users.
945 * If the length of a single line is more than 480-NICKMAX
946 * in length, it is split over multiple lines.
948 void SendFJoins(TreeServer* Current, chanrec* c)
951 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
952 std::vector<char*> *ulist = c->GetUsers();
953 for (unsigned int i = 0; i < ulist->size(); i++)
955 char* o = (*ulist)[i];
956 userrec* otheruser = (userrec*)o;
957 strlcat(list," ",MAXBUF);
958 strlcat(list,cmode(otheruser,c),MAXBUF);
959 strlcat(list,otheruser->nick,MAXBUF);
960 if (strlen(list)>(480-NICKMAX))
962 this->WriteLine(list);
963 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
966 if (list[strlen(list)-1] != ':')
968 this->WriteLine(list);
972 /* Send G, Q, Z and E lines */
973 void SendXLines(TreeServer* Current)
976 /* Yes, these arent too nice looking, but they get the job done */
977 for (std::vector<ZLine>::iterator i = zlines.begin(); i != zlines.end(); i++)
979 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);
980 this->WriteLine(data);
982 for (std::vector<QLine>::iterator i = qlines.begin(); i != qlines.end(); i++)
984 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);
985 this->WriteLine(data);
987 for (std::vector<GLine>::iterator i = glines.begin(); i != glines.end(); i++)
989 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);
990 this->WriteLine(data);
992 for (std::vector<ELine>::iterator i = elines.begin(); i != elines.end(); i++)
994 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);
995 this->WriteLine(data);
999 /* Send channel modes and topics */
1000 void SendChannelModes(TreeServer* Current)
1003 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
1005 SendFJoins(Current, c->second);
1006 snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
1007 this->WriteLine(data);
1008 if (*c->second->topic)
1010 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);
1011 this->WriteLine(data);
1013 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
1015 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
1016 this->WriteLine(data);
1018 FOREACH_MOD OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this);
1022 /* send all users and their oper state/modes */
1023 void SendUsers(TreeServer* Current)
1026 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
1028 if (u->second->registered == 7)
1030 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);
1031 this->WriteLine(data);
1032 if (strchr(u->second->modes,'o'))
1034 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
1036 //char* chl = chlist(u->second,u->second);
1039 // this->WriteLine(":"+std::string(u->second->nick)+" FJOIN "+std::string(chl));
1041 FOREACH_MOD OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this);
1046 /* This function is called when we want to send a netburst to a local
1047 * server. There is a set order we must do this, because for example
1048 * users require their servers to exist, and channels require their
1049 * users to exist. You get the idea.
1051 void DoBurst(TreeServer* s)
1053 Srv->SendOpers("*** Bursting to \2"+s->GetName()+"\2.");
1054 this->WriteLine("BURST");
1055 /* send our version string */
1056 this->WriteLine(":"+Srv->GetServerName()+" VERSION :"+GetVersionString());
1057 /* Send server tree */
1058 this->SendServers(TreeRoot,s,1);
1059 /* Send users and their oper status */
1061 /* Send everything else (channel modes, xlines etc) */
1062 this->SendChannelModes(s);
1063 this->SendXLines(s);
1064 this->WriteLine("ENDBURST");
1065 Srv->SendOpers("*** Finished bursting to \2"+s->GetName()+"\2.");
1068 /* This function is called when we receive data from a remote
1069 * server. We buffer the data in a std::string (it doesnt stay
1070 * there for long), reading using InspSocket::Read() which can
1071 * read up to 16 kilobytes in one operation.
1073 * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
1074 * THE SOCKET OBJECT FOR US.
1076 virtual bool OnDataReady()
1078 char* data = this->Read();
1081 this->in_buffer += data;
1082 /* While there is at least one new line in the buffer,
1083 * do something useful (we hope!) with it.
1085 while (in_buffer.find("\n") != std::string::npos)
1087 char* line = (char*)in_buffer.c_str();
1088 std::string ret = "";
1089 while ((*line != '\n') && (strlen(line)))
1094 if ((*line == '\n') || (*line == '\r'))
1097 /* Process this one, abort if it
1098 * didnt return true.
1100 if (!this->ProcessLine(ret))
1106 return (data != NULL);
1109 int WriteLine(std::string line)
1111 return this->Write(line + "\r\n");
1114 /* Handle ERROR command */
1115 bool Error(std::deque<std::string> params)
1117 if (params.size() < 1)
1119 std::string Errmsg = params[0];
1120 std::string SName = myhost;
1121 if (InboundServerName != "")
1123 SName = InboundServerName;
1125 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
1126 /* we will return false to cause the socket to close.
1131 /* Because the core won't let users or even SERVERS set +o,
1132 * we use the OPERTYPE command to do this.
1134 bool OperType(std::string prefix, std::deque<std::string> params)
1136 if (params.size() != 1)
1138 std::string opertype = params[0];
1139 userrec* u = Srv->FindNick(prefix);
1142 strlcpy(u->oper,opertype.c_str(),NICKMAX);
1143 if (!strchr(u->modes,'o'))
1145 strcat(u->modes,"o");
1147 DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
1152 /* Because Andy insists that services-compatible servers must
1153 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
1155 bool ForceNick(std::string prefix, std::deque<std::string> params)
1157 if (params.size() < 3)
1159 userrec* u = Srv->FindNick(params[0]);
1162 Srv->ChangeUserNick(u,params[1]);
1163 u->age = atoi(params[2].c_str());
1164 DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
1169 bool ServiceJoin(std::string prefix, std::deque<std::string> params)
1171 if (params.size() < 2)
1173 userrec* u = Srv->FindNick(params[0]);
1176 Srv->JoinUserToChannel(u,params[1],"");
1177 DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
1182 bool RemoteRehash(std::string prefix, std::deque<std::string> params)
1184 if (params.size() < 1)
1186 std::string servermask = params[0];
1187 if (Srv->MatchText(Srv->GetServerName(),servermask))
1189 Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
1190 Srv->RehashServer();
1191 ReadConfiguration(false);
1193 DoOneToAllButSender(prefix,"REHASH",params,prefix);
1197 bool RemoteKill(std::string prefix, std::deque<std::string> params)
1199 if (params.size() != 2)
1201 std::string nick = params[0];
1202 userrec* u = Srv->FindNick(prefix);
1203 userrec* who = Srv->FindNick(nick);
1206 /* Append kill source, if we don't have one */
1207 if (*(params[1].c_str()) != '[')
1209 params[1] = "[" + std::string(u->server) + "] Killed (" + params[1] +")";
1211 std::string sourceserv = prefix;
1214 sourceserv = u->server;
1216 params[1] = ":" + params[1];
1217 DoOneToAllButSender(prefix,"KILL",params,sourceserv);
1218 Srv->QuitUser(who,params[1]);
1223 bool LocalPong(std::string prefix, std::deque<std::string> params)
1225 if (params.size() < 1)
1227 TreeServer* ServerSource = FindServer(prefix);
1230 ServerSource->SetPingFlag();
1235 bool ServerVersion(std::string prefix, std::deque<std::string> params)
1237 if (params.size() < 1)
1239 TreeServer* ServerSource = FindServer(prefix);
1242 ServerSource->SetVersion(params[0]);
1244 params[0] = ":" + params[0];
1245 DoOneToAllButSender(prefix,"VERSION",params,prefix);
1249 bool ChangeHost(std::string prefix, std::deque<std::string> params)
1251 if (params.size() < 1)
1253 userrec* u = Srv->FindNick(prefix);
1256 Srv->ChangeHost(u,params[0]);
1257 DoOneToAllButSender(prefix,"FHOST",params,u->server);
1262 bool AddLine(std::string prefix, std::deque<std::string> params)
1264 if (params.size() < 6)
1266 std::string linetype = params[0]; /* Z, Q, E, G, K */
1267 std::string mask = params[1]; /* Line type dependent */
1268 std::string source = params[2]; /* may not be online or may be a server */
1269 std::string settime = params[3]; /* EPOCH time set */
1270 std::string duration = params[4]; /* Duration secs */
1271 std::string reason = params[5];
1273 switch (*(linetype.c_str()))
1276 add_zline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1279 add_qline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1282 add_eline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1285 add_gline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1288 add_kline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1291 /* Just in case... */
1292 Srv->SendOpers("*** \2WARNING\2: Invalid xline type '"+linetype+"' sent by server "+prefix+", ignored!");
1295 /* Send it on its way */
1296 params[5] = ":" + params[5];
1297 DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
1301 bool ChangeName(std::string prefix, std::deque<std::string> params)
1303 if (params.size() < 1)
1305 userrec* u = Srv->FindNick(prefix);
1308 Srv->ChangeGECOS(u,params[0]);
1309 params[0] = ":" + params[0];
1310 DoOneToAllButSender(prefix,"FNAME",params,u->server);
1315 bool LocalPing(std::string prefix, std::deque<std::string> params)
1317 if (params.size() < 1)
1319 std::string stufftobounce = params[0];
1320 this->WriteLine(":"+Srv->GetServerName()+" PONG "+stufftobounce);
1324 bool RemoteServer(std::string prefix, std::deque<std::string> params)
1326 if (params.size() < 4)
1328 std::string servername = params[0];
1329 std::string password = params[1];
1330 // hopcount is not used for a remote server, we calculate this ourselves
1331 std::string description = params[3];
1332 TreeServer* ParentOfThis = FindServer(prefix);
1335 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
1338 TreeServer* CheckDupe = FindServer(servername);
1341 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1344 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
1345 ParentOfThis->AddChild(Node);
1346 params[3] = ":" + params[3];
1347 DoOneToAllButSender(prefix,"SERVER",params,prefix);
1348 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
1352 bool Outbound_Reply_Server(std::deque<std::string> params)
1354 if (params.size() < 4)
1356 std::string servername = params[0];
1357 std::string password = params[1];
1358 int hops = atoi(params[2].c_str());
1361 this->WriteLine("ERROR :Server too far away for authentication");
1364 std::string description = params[3];
1365 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1367 if ((x->Name == servername) && (x->RecvPass == password))
1369 TreeServer* CheckDupe = FindServer(servername);
1372 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1375 // Begin the sync here. this kickstarts the
1376 // other side, waiting in WAIT_AUTH_2 state,
1377 // into starting their burst, as it shows
1378 // that we're happy.
1379 this->LinkState = CONNECTED;
1380 // we should add the details of this server now
1381 // to the servers tree, as a child of the root
1383 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
1384 TreeRoot->AddChild(Node);
1385 params[3] = ":" + params[3];
1386 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
1387 this->DoBurst(Node);
1391 this->WriteLine("ERROR :Invalid credentials");
1395 bool Inbound_Server(std::deque<std::string> params)
1397 if (params.size() < 4)
1399 std::string servername = params[0];
1400 std::string password = params[1];
1401 int hops = atoi(params[2].c_str());
1404 this->WriteLine("ERROR :Server too far away for authentication");
1407 std::string description = params[3];
1408 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1410 if ((x->Name == servername) && (x->RecvPass == password))
1412 TreeServer* CheckDupe = FindServer(servername);
1415 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1418 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
1419 this->InboundServerName = servername;
1420 this->InboundDescription = description;
1421 // this is good. Send our details: Our server name and description and hopcount of 0,
1422 // along with the sendpass from this block.
1423 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
1424 // move to the next state, we are now waiting for THEM.
1425 this->LinkState = WAIT_AUTH_2;
1429 this->WriteLine("ERROR :Invalid credentials");
1433 std::deque<std::string> Split(std::string line, bool stripcolon)
1435 std::deque<std::string> n;
1436 if (!strchr(line.c_str(),' '))
1441 std::stringstream s(line);
1442 std::string param = "";
1461 if ((param == ":") && (item > 0))
1484 bool ProcessLine(std::string line)
1486 char* l = (char*)line.c_str();
1487 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
1488 l[strlen(l)-1] = '\0';
1492 Srv->Log(DEBUG,"IN: '"+line+"'");
1493 std::deque<std::string> params = this->Split(line,true);
1494 std::string command = "";
1495 std::string prefix = "";
1496 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
1499 command = params[1];
1500 char* pref = (char*)prefix.c_str();
1508 command = params[0];
1512 switch (this->LinkState)
1517 // Waiting for SERVER command from remote server. Server initiating
1518 // the connection sends the first SERVER command, listening server
1519 // replies with theirs if its happy, then if the initiator is happy,
1520 // it starts to send its net sync, which starts the merge, otherwise
1521 // it sends an ERROR.
1522 if (command == "SERVER")
1524 return this->Inbound_Server(params);
1526 else if (command == "ERROR")
1528 return this->Error(params);
1532 // Waiting for start of other side's netmerge to say they liked our
1534 if (command == "SERVER")
1536 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1540 else if (command == "BURST")
1542 this->LinkState = CONNECTED;
1543 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
1544 TreeRoot->AddChild(Node);
1546 params.push_back(InboundServerName);
1547 params.push_back("*");
1548 params.push_back("1");
1549 params.push_back(":"+InboundDescription);
1550 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
1551 this->DoBurst(Node);
1553 else if (command == "ERROR")
1555 return this->Error(params);
1560 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
1564 if (command == "SERVER")
1566 // another server we connected to, which was in WAIT_AUTH_1 state,
1567 // has just sent us their credentials. If we get this far, theyre
1568 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1569 // if we're happy with this, we should send our netburst which
1570 // kickstarts the merge.
1571 return this->Outbound_Reply_Server(params);
1573 else if (command == "ERROR")
1575 return this->Error(params);
1579 // This is the 'authenticated' state, when all passwords
1580 // have been exchanged and anything past this point is taken
1582 if (command == "SVSMODE")
1584 /* Services expects us to implement
1585 * SVSMODE. In inspircd its the same as
1590 std::string target = "";
1591 /* Yes, know, this is a mess. Its reasonably fast though as we're
1592 * working with std::string here.
1594 if ((command == "NICK") && (params.size() > 1))
1596 return this->IntroduceClient(prefix,params);
1598 else if (command == "FJOIN")
1600 return this->ForceJoin(prefix,params);
1602 else if (command == "SERVER")
1604 return this->RemoteServer(prefix,params);
1606 else if (command == "ERROR")
1608 return this->Error(params);
1610 else if (command == "OPERTYPE")
1612 return this->OperType(prefix,params);
1614 else if (command == "FMODE")
1616 return this->ForceMode(prefix,params);
1618 else if (command == "KILL")
1620 return this->RemoteKill(prefix,params);
1622 else if (command == "FTOPIC")
1624 return this->ForceTopic(prefix,params);
1626 else if (command == "REHASH")
1628 return this->RemoteRehash(prefix,params);
1630 else if (command == "PING")
1632 return this->LocalPing(prefix,params);
1634 else if (command == "PONG")
1636 return this->LocalPong(prefix,params);
1638 else if (command == "VERSION")
1640 return this->ServerVersion(prefix,params);
1642 else if (command == "FHOST")
1644 return this->ChangeHost(prefix,params);
1646 else if (command == "FNAME")
1648 return this->ChangeName(prefix,params);
1650 else if (command == "ADDLINE")
1652 return this->AddLine(prefix,params);
1654 else if (command == "SVSNICK")
1658 prefix = this->GetName();
1660 return this->ForceNick(prefix,params);
1662 else if (command == "SVSJOIN")
1666 prefix = this->GetName();
1668 return this->ServiceJoin(prefix,params);
1670 else if (command == "SQUIT")
1672 if (params.size() == 2)
1674 this->Squit(FindServer(params[0]),params[1]);
1680 // not a special inter-server command.
1681 // Emulate the actual user doing the command,
1682 // this saves us having a huge ugly parser.
1683 userrec* who = Srv->FindNick(prefix);
1684 std::string sourceserv = this->myhost;
1685 if (this->InboundServerName != "")
1687 sourceserv = this->InboundServerName;
1692 target = who->server;
1693 char* strparams[127];
1694 for (unsigned int q = 0; q < params.size(); q++)
1696 strparams[q] = (char*)params[q].c_str();
1698 Srv->CallCommandHandler(command, strparams, params.size(), who);
1702 // its not a user. Its either a server, or somethings screwed up.
1703 if (IsServer(prefix))
1705 target = Srv->GetServerName();
1709 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
1713 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1722 virtual std::string GetName()
1724 std::string sourceserv = this->myhost;
1725 if (this->InboundServerName != "")
1727 sourceserv = this->InboundServerName;
1732 virtual void OnTimeout()
1734 if (this->LinkState == CONNECTING)
1736 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
1740 virtual void OnClose()
1742 // Connection closed.
1743 // If the connection is fully up (state CONNECTED)
1744 // then propogate a netsplit to all peers.
1745 std::string quitserver = this->myhost;
1746 if (this->InboundServerName != "")
1748 quitserver = this->InboundServerName;
1750 TreeServer* s = FindServer(quitserver);
1753 Squit(s,"Remote host closed the connection");
1757 virtual int OnIncomingConnection(int newsock, char* ip)
1759 TreeSocket* s = new TreeSocket(newsock, ip);
1765 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
1767 for (unsigned int c = 0; c < list.size(); c++)
1769 if (list[c] == server)
1774 list.push_back(server);
1777 // returns a list of DIRECT servernames for a specific channel
1778 void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
1780 std::vector<char*> *ulist = c->GetUsers();
1781 unsigned int ucount = ulist->size();
1782 for (unsigned int i = 0; i < ucount; i++)
1784 char* o = (*ulist)[i];
1785 userrec* otheruser = (userrec*)o;
1786 if (std::string(otheruser->server) != Srv->GetServerName())
1788 TreeServer* best = BestRouteTo(otheruser->server);
1790 AddThisServer(best,list);
1796 bool DoOneToAllButSenderRaw(std::string data,std::string omit,std::string prefix,std::string command,std::deque<std::string> params)
1798 TreeServer* omitroute = BestRouteTo(omit);
1799 if ((command == "NOTICE") || (command == "PRIVMSG"))
1801 if ((params.size() >= 2) && (*(params[0].c_str()) != '$'))
1803 if (*(params[0].c_str()) != '#')
1805 // special routing for private messages/notices
1806 userrec* d = Srv->FindNick(params[0]);
1809 std::deque<std::string> par;
1810 par.push_back(params[0]);
1811 par.push_back(":"+params[1]);
1812 DoOneToOne(prefix,command,par,d->server);
1818 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
1819 chanrec* c = Srv->FindChannel(params[0]);
1822 std::deque<TreeServer*> list;
1823 GetListOfServersForChannel(c,list);
1824 log(DEBUG,"Got a list of %d servers",list.size());
1825 unsigned int lsize = list.size();
1826 for (unsigned int i = 0; i < lsize; i++)
1828 TreeSocket* Sock = list[i]->GetSocket();
1829 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
1831 log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
1832 Sock->WriteLine(data);
1840 unsigned int items = TreeRoot->ChildCount();
1841 for (unsigned int x = 0; x < items; x++)
1843 TreeServer* Route = TreeRoot->GetChild(x);
1844 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1846 TreeSocket* Sock = Route->GetSocket();
1847 Sock->WriteLine(data);
1853 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit)
1855 TreeServer* omitroute = BestRouteTo(omit);
1856 std::string FullLine = ":" + prefix + " " + command;
1857 unsigned int words = params.size();
1858 for (unsigned int x = 0; x < words; x++)
1860 FullLine = FullLine + " " + params[x];
1862 unsigned int items = TreeRoot->ChildCount();
1863 for (unsigned int x = 0; x < items; x++)
1865 TreeServer* Route = TreeRoot->GetChild(x);
1866 // Send the line IF:
1867 // The route has a socket (its a direct connection)
1868 // The route isnt the one to be omitted
1869 // The route isnt the path to the one to be omitted
1870 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1872 TreeSocket* Sock = Route->GetSocket();
1873 Sock->WriteLine(FullLine);
1879 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params)
1881 std::string FullLine = ":" + prefix + " " + command;
1882 unsigned int words = params.size();
1883 for (unsigned int x = 0; x < words; x++)
1885 FullLine = FullLine + " " + params[x];
1887 unsigned int items = TreeRoot->ChildCount();
1888 for (unsigned int x = 0; x < items; x++)
1890 TreeServer* Route = TreeRoot->GetChild(x);
1891 if (Route->GetSocket())
1893 TreeSocket* Sock = Route->GetSocket();
1894 Sock->WriteLine(FullLine);
1900 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target)
1902 TreeServer* Route = BestRouteTo(target);
1905 std::string FullLine = ":" + prefix + " " + command;
1906 unsigned int words = params.size();
1907 for (unsigned int x = 0; x < words; x++)
1909 FullLine = FullLine + " " + params[x];
1911 if (Route->GetSocket())
1913 TreeSocket* Sock = Route->GetSocket();
1914 Sock->WriteLine(FullLine);
1924 std::vector<TreeSocket*> Bindings;
1926 void ReadConfiguration(bool rebind)
1930 for (int j =0; j < Conf->Enumerate("bind"); j++)
1932 std::string Type = Conf->ReadValue("bind","type",j);
1933 std::string IP = Conf->ReadValue("bind","address",j);
1934 long Port = Conf->ReadInteger("bind","port",j,true);
1935 if (Type == "servers")
1941 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
1942 if (listener->GetState() == I_LISTENING)
1944 Srv->AddSocket(listener);
1945 Bindings.push_back(listener);
1949 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
1957 for (int j =0; j < Conf->Enumerate("link"); j++)
1960 L.Name = Conf->ReadValue("link","name",j);
1961 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
1962 L.Port = Conf->ReadInteger("link","port",j,true);
1963 L.SendPass = Conf->ReadValue("link","sendpass",j);
1964 L.RecvPass = Conf->ReadValue("link","recvpass",j);
1965 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
1966 L.NextConnectTime = time(NULL) + L.AutoConnect;
1967 LinkBlocks.push_back(L);
1968 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
1973 class ModuleSpanningTree : public Module
1975 std::vector<TreeSocket*> Bindings;
1981 ModuleSpanningTree()
1984 Conf = new ConfigReader;
1987 // Create the root of the tree
1988 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
1990 ReadConfiguration(true);
1993 void ShowLinks(TreeServer* Current, userrec* user, int hops)
1995 std::string Parent = TreeRoot->GetName();
1996 if (Current->GetParent())
1998 Parent = Current->GetParent()->GetName();
2000 for (unsigned int q = 0; q < Current->ChildCount(); q++)
2002 ShowLinks(Current->GetChild(q),user,hops+1);
2004 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
2007 int CountLocalServs()
2009 return TreeRoot->ChildCount();
2012 void CountServsRecursive(TreeServer* Current)
2015 for (unsigned int q = 0; q < Current->ChildCount(); q++)
2017 CountServsRecursive(Current->GetChild(q));
2024 CountServsRecursive(TreeRoot);
2028 void HandleLinks(char** parameters, int pcnt, userrec* user)
2030 ShowLinks(TreeRoot,user,0);
2031 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
2035 void HandleLusers(char** parameters, int pcnt, userrec* user)
2037 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),this->CountServs());
2038 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
2039 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
2040 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
2041 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
2045 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
2047 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
2051 for (int t = 0; t < depth; t++)
2053 matrix[line][t] = ' ';
2055 strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
2057 for (unsigned int q = 0; q < Current->ChildCount(); q++)
2059 ShowMap(Current->GetChild(q),user,depth+2,matrix);
2064 // Ok, prepare to be confused.
2065 // After much mulling over how to approach this, it struck me that
2066 // the 'usual' way of doing a /MAP isnt the best way. Instead of
2067 // keeping track of a ton of ascii characters, and line by line
2068 // under recursion working out where to place them using multiplications
2069 // and divisons, we instead render the map onto a backplane of characters
2070 // (a character matrix), then draw the branches as a series of "L" shapes
2071 // from the nodes. This is not only friendlier on CPU it uses less stack.
2073 void HandleMap(char** parameters, int pcnt, userrec* user)
2075 // This array represents a virtual screen which we will
2076 // "scratch" draw to, as the console device of an irc
2077 // client does not provide for a proper terminal.
2078 char matrix[128][80];
2079 for (unsigned int t = 0; t < 128; t++)
2081 matrix[t][0] = '\0';
2084 // The only recursive bit is called here.
2085 ShowMap(TreeRoot,user,0,matrix);
2086 // Process each line one by one. The algorithm has a limit of
2087 // 128 servers (which is far more than a spanning tree should have
2088 // anyway, so we're ok). This limit can be raised simply by making
2089 // the character matrix deeper, 128 rows taking 10k of memory.
2090 for (int l = 1; l < line; l++)
2092 // scan across the line looking for the start of the
2093 // servername (the recursive part of the algorithm has placed
2094 // the servers at indented positions depending on what they
2096 int first_nonspace = 0;
2097 while (matrix[l][first_nonspace] == ' ')
2102 // Draw the `- (corner) section: this may be overwritten by
2103 // another L shape passing along the same vertical pane, becoming
2104 // a |- (branch) section instead.
2105 matrix[l][first_nonspace] = '-';
2106 matrix[l][first_nonspace-1] = '`';
2108 // Draw upwards until we hit the parent server, causing possibly
2109 // other corners (`-) to become branches (|-)
2110 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
2112 matrix[l2][first_nonspace-1] = '|';
2116 // dump the whole lot to the user. This is the easy bit, honest.
2117 for (int t = 0; t < line; t++)
2119 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
2121 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
2125 int HandleSquit(char** parameters, int pcnt, userrec* user)
2127 TreeServer* s = FindServerMask(parameters[0]);
2130 TreeSocket* sock = s->GetSocket();
2133 WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
2134 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
2139 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
2144 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
2149 void DoPingChecks(time_t curtime)
2151 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
2153 TreeServer* serv = TreeRoot->GetChild(j);
2154 TreeSocket* sock = serv->GetSocket();
2157 if (curtime >= serv->NextPingTime())
2159 if (serv->AnsweredLastPing())
2161 sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
2162 serv->SetNextPingTime(curtime + 60);
2166 // they didnt answer, boot them
2167 WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
2168 sock->Squit(serv,"Ping timeout");
2177 void AutoConnectServers(time_t curtime)
2179 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2181 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
2183 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
2184 x->NextConnectTime = curtime + x->AutoConnect;
2185 TreeServer* CheckDupe = FindServer(x->Name);
2188 // an autoconnected server is not connected. Check if its time to connect it
2189 WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
2190 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2191 Srv->AddSocket(newsocket);
2197 int HandleVersion(char** parameters, int pcnt, userrec* user)
2199 // we've already checked if pcnt > 0, so this is safe
2200 TreeServer* found = FindServerMask(parameters[0]);
2203 std::string Version = found->GetVersion();
2204 WriteServ(user->fd,"351 %s :%s",user->nick,Version.c_str());
2208 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
2213 int HandleConnect(char** parameters, int pcnt, userrec* user)
2215 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2217 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
2219 TreeServer* CheckDupe = FindServer(x->Name);
2222 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);
2223 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2224 Srv->AddSocket(newsocket);
2229 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());
2234 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
2238 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
2240 if (command == "CONNECT")
2242 return this->HandleConnect(parameters,pcnt,user);
2244 else if (command == "SQUIT")
2246 return this->HandleSquit(parameters,pcnt,user);
2248 else if (command == "MAP")
2250 this->HandleMap(parameters,pcnt,user);
2253 else if (command == "LUSERS")
2255 this->HandleLusers(parameters,pcnt,user);
2258 else if (command == "LINKS")
2260 this->HandleLinks(parameters,pcnt,user);
2263 else if ((command == "VERSION") && (pcnt > 0))
2265 this->HandleVersion(parameters,pcnt,user);
2268 else if (Srv->IsValidModuleCommand(command, pcnt, user))
2270 // this bit of code cleverly routes all module commands
2271 // to all remote severs *automatically* so that modules
2272 // can just handle commands locally, without having
2273 // to have any special provision in place for remote
2274 // commands and linking protocols.
2275 std::deque<std::string> params;
2277 for (int j = 0; j < pcnt; j++)
2279 if (strchr(parameters[j],' '))
2281 params.push_back(":" + std::string(parameters[j]));
2285 params.push_back(std::string(parameters[j]));
2288 DoOneToMany(user->nick,command,params);
2293 virtual void OnGetServerDescription(std::string servername,std::string &description)
2295 TreeServer* s = FindServer(servername);
2298 description = s->GetDesc();
2302 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
2304 if (std::string(source->server) == Srv->GetServerName())
2306 std::deque<std::string> params;
2307 params.push_back(dest->nick);
2308 params.push_back(channel->name);
2309 DoOneToMany(source->nick,"INVITE",params);
2313 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
2315 std::deque<std::string> params;
2316 params.push_back(chan->name);
2317 params.push_back(":"+topic);
2318 DoOneToMany(user->nick,"TOPIC",params);
2321 virtual void OnWallops(userrec* user, std::string text)
2323 if (std::string(user->server) == Srv->GetServerName())
2325 std::deque<std::string> params;
2326 params.push_back(":"+text);
2327 DoOneToMany(user->nick,"WALLOPS",params);
2331 virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
2333 if (target_type == TYPE_USER)
2335 userrec* d = (userrec*)dest;
2336 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
2338 std::deque<std::string> params;
2340 params.push_back(d->nick);
2341 params.push_back(":"+text);
2342 DoOneToOne(user->nick,"NOTICE",params,d->server);
2347 if (std::string(user->server) == Srv->GetServerName())
2349 chanrec *c = (chanrec*)dest;
2350 std::deque<TreeServer*> list;
2351 GetListOfServersForChannel(c,list);
2352 unsigned int ucount = list.size();
2353 for (unsigned int i = 0; i < ucount; i++)
2355 TreeSocket* Sock = list[i]->GetSocket();
2357 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+std::string(c->name)+" :"+text);
2363 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
2365 if (target_type == TYPE_USER)
2367 // route private messages which are targetted at clients only to the server
2368 // which needs to receive them
2369 userrec* d = (userrec*)dest;
2370 if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
2372 std::deque<std::string> params;
2374 params.push_back(d->nick);
2375 params.push_back(":"+text);
2376 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
2381 if (std::string(user->server) == Srv->GetServerName())
2383 chanrec *c = (chanrec*)dest;
2384 std::deque<TreeServer*> list;
2385 GetListOfServersForChannel(c,list);
2386 unsigned int ucount = list.size();
2387 for (unsigned int i = 0; i < ucount; i++)
2389 TreeSocket* Sock = list[i]->GetSocket();
2391 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+std::string(c->name)+" :"+text);
2397 virtual void OnBackgroundTimer(time_t curtime)
2399 AutoConnectServers(curtime);
2400 DoPingChecks(curtime);
2403 virtual void OnUserJoin(userrec* user, chanrec* channel)
2405 // Only do this for local users
2406 if (std::string(user->server) == Srv->GetServerName())
2408 std::deque<std::string> params;
2410 params.push_back(channel->name);
2413 // if the channel has a key, force the join by emulating the key.
2414 params.push_back(channel->key);
2416 if (channel->GetUserCounter() > 1)
2418 // not the first in the channel
2419 DoOneToMany(user->nick,"JOIN",params);
2423 // first in the channel, set up their permissions
2424 // and the channel TS with FJOIN.
2426 snprintf(ts,24,"%lu",(unsigned long)channel->age);
2428 params.push_back(channel->name);
2429 params.push_back(ts);
2430 params.push_back("@"+std::string(user->nick));
2431 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
2436 virtual void OnChangeHost(userrec* user, std::string newhost)
2438 // only occurs for local clients
2439 std::deque<std::string> params;
2440 params.push_back(newhost);
2441 DoOneToMany(user->nick,"FHOST",params);
2444 virtual void OnChangeName(userrec* user, std::string gecos)
2446 // only occurs for local clients
2447 std::deque<std::string> params;
2448 params.push_back(gecos);
2449 DoOneToMany(user->nick,"FNAME",params);
2452 virtual void OnUserPart(userrec* user, chanrec* channel)
2454 if (std::string(user->server) == Srv->GetServerName())
2456 std::deque<std::string> params;
2457 params.push_back(channel->name);
2458 DoOneToMany(user->nick,"PART",params);
2462 virtual void OnUserConnect(userrec* user)
2464 char agestr[MAXBUF];
2465 if (std::string(user->server) == Srv->GetServerName())
2467 std::deque<std::string> params;
2468 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
2469 params.push_back(agestr);
2470 params.push_back(user->nick);
2471 params.push_back(user->host);
2472 params.push_back(user->dhost);
2473 params.push_back(user->ident);
2474 params.push_back("+"+std::string(user->modes));
2475 params.push_back(user->ip);
2476 params.push_back(":"+std::string(user->fullname));
2477 DoOneToMany(Srv->GetServerName(),"NICK",params);
2481 virtual void OnUserQuit(userrec* user, std::string reason)
2483 if (std::string(user->server) == Srv->GetServerName())
2485 std::deque<std::string> params;
2486 params.push_back(":"+reason);
2487 DoOneToMany(user->nick,"QUIT",params);
2491 virtual void OnUserPostNick(userrec* user, std::string oldnick)
2493 if (std::string(user->server) == Srv->GetServerName())
2495 std::deque<std::string> params;
2496 params.push_back(user->nick);
2497 DoOneToMany(oldnick,"NICK",params);
2501 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
2503 if (std::string(source->server) == Srv->GetServerName())
2505 std::deque<std::string> params;
2506 params.push_back(chan->name);
2507 params.push_back(user->nick);
2508 params.push_back(":"+reason);
2509 DoOneToMany(source->nick,"KICK",params);
2513 virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
2515 std::deque<std::string> params;
2516 params.push_back(dest->nick);
2517 params.push_back(":"+reason);
2518 DoOneToMany(source->nick,"KILL",params);
2521 virtual void OnRehash(std::string parameter)
2523 if (parameter != "")
2525 std::deque<std::string> params;
2526 params.push_back(parameter);
2527 DoOneToMany(Srv->GetServerName(),"REHASH",params);
2529 if (Srv->MatchText(Srv->GetServerName(),parameter))
2531 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
2532 Srv->RehashServer();
2535 ReadConfiguration(false);
2538 // note: the protocol does not allow direct umode +o except
2539 // via NICK with 8 params. sending OPERTYPE infers +o modechange
2541 virtual void OnOper(userrec* user, std::string opertype)
2543 if (std::string(user->server) == Srv->GetServerName())
2545 std::deque<std::string> params;
2546 params.push_back(opertype);
2547 DoOneToMany(user->nick,"OPERTYPE",params);
2551 void OnLine(userrec* source, std::string host, bool adding, char linetype, long duration, std::string reason)
2553 if (std::string(source->server) == Srv->GetServerName())
2556 snprintf(type,8,"%cLINE",linetype);
2557 std::string stype = type;
2560 char sduration[MAXBUF];
2561 snprintf(sduration,MAXBUF,"%ld",duration);
2562 std::deque<std::string> params;
2563 params.push_back(host);
2564 params.push_back(sduration);
2565 params.push_back(":"+reason);
2566 DoOneToMany(source->nick,stype,params);
2570 std::deque<std::string> params;
2571 params.push_back(host);
2572 DoOneToMany(source->nick,stype,params);
2577 virtual void OnAddGLine(long duration, userrec* source, std::string reason, std::string hostmask)
2579 OnLine(source,hostmask,true,'G',duration,reason);
2582 virtual void OnAddZLine(long duration, userrec* source, std::string reason, std::string ipmask)
2584 OnLine(source,ipmask,true,'Z',duration,reason);
2587 virtual void OnAddQLine(long duration, userrec* source, std::string reason, std::string nickmask)
2589 OnLine(source,nickmask,true,'Q',duration,reason);
2592 virtual void OnAddELine(long duration, userrec* source, std::string reason, std::string hostmask)
2594 OnLine(source,hostmask,true,'E',duration,reason);
2597 virtual void OnDelGLine(userrec* source, std::string hostmask)
2599 OnLine(source,hostmask,false,'G',0,"");
2602 virtual void OnDelZLine(userrec* source, std::string ipmask)
2604 OnLine(source,ipmask,false,'Z',0,"");
2607 virtual void OnDelQLine(userrec* source, std::string nickmask)
2609 OnLine(source,nickmask,false,'Q',0,"");
2612 virtual void OnDelELine(userrec* source, std::string hostmask)
2614 OnLine(source,hostmask,false,'E',0,"");
2617 virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
2619 if (std::string(user->server) == Srv->GetServerName())
2621 if (target_type == TYPE_USER)
2623 userrec* u = (userrec*)dest;
2624 std::deque<std::string> params;
2625 params.push_back(u->nick);
2626 params.push_back(text);
2627 DoOneToMany(user->nick,"MODE",params);
2631 chanrec* c = (chanrec*)dest;
2632 std::deque<std::string> params;
2633 params.push_back(c->name);
2634 params.push_back(text);
2635 DoOneToMany(user->nick,"MODE",params);
2640 virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
2642 TreeSocket* s = (TreeSocket*)opaque;
2645 if (target_type == TYPE_USER)
2647 userrec* u = (userrec*)target;
2648 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
2652 chanrec* c = (chanrec*)target;
2653 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
2658 virtual ~ModuleSpanningTree()
2663 virtual Version GetVersion()
2665 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
2670 class ModuleSpanningTreeFactory : public ModuleFactory
2673 ModuleSpanningTreeFactory()
2677 ~ModuleSpanningTreeFactory()
2681 virtual Module * CreateModule()
2683 TreeProtocolModule = new ModuleSpanningTree;
2684 return TreeProtocolModule;
2690 extern "C" void * init_module( void )
2692 return new ModuleSpanningTreeFactory;