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"
43 #include "cull_list.h"
47 #define nspace __gnu_cxx
53 * The server list in InspIRCd is maintained as two structures
54 * which hold the data in different ways. Most of the time, we
55 * want to very quicky obtain three pieces of information:
57 * (1) The information on a server
58 * (2) The information on the server we must send data through
59 * to actually REACH the server we're after
60 * (3) Potentially, the child/parent objects of this server
62 * The InspIRCd spanning protocol provides easy access to these
63 * by storing the data firstly in a recursive structure, where
64 * each item references its parent item, and a dynamic list
65 * of child items, and another structure which stores the items
66 * hashed, linearly. This means that if we want to find a server
67 * by name quickly, we can look it up in the hash, avoiding
68 * any O(n) lookups. If however, during a split or sync, we want
69 * to apply an operation to a server, and any of its child objects
70 * we can resort to recursion to walk the tree structure.
73 class ModuleSpanningTree;
74 static ModuleSpanningTree* TreeProtocolModule;
76 extern std::vector<Module*> modules;
77 extern std::vector<ircd_module*> factory;
80 /* Any socket can have one of five states at any one time.
81 * The LISTENER state indicates a socket which is listening
82 * for connections. It cannot receive data itself, only incoming
84 * The CONNECTING state indicates an outbound socket which is
85 * waiting to be writeable.
86 * The WAIT_AUTH_1 state indicates the socket is outbound and
87 * has successfully connected, but has not yet sent and received
89 * The WAIT_AUTH_2 state indicates that the socket is inbound
90 * (allocated by a LISTENER) but has not yet sent and received
92 * The CONNECTED state represents a fully authorized, fully
95 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
97 /* We need to import these from the core for use in netbursts */
98 /*typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
99 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;*/
100 extern user_hash clientlist;
101 extern chan_hash chanlist;
103 /* Foward declarations */
107 /* This variable represents the root of the server tree
108 * (for all intents and purposes, it's us)
110 TreeServer *TreeRoot;
114 /* This hash_map holds the hash equivalent of the server
115 * tree, used for rapid linear lookups.
117 typedef nspace::hash_map<std::string, TreeServer*> server_hash;
118 server_hash serverlist;
120 /* More forward declarations */
121 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string target);
122 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string omit);
123 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> ¶ms);
124 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, std::string command, std::deque<std::string> ¶ms);
125 void ReadConfiguration(bool rebind);
127 /* Imported from xline.cpp for use during netburst */
128 extern std::vector<KLine> klines;
129 extern std::vector<GLine> glines;
130 extern std::vector<ZLine> zlines;
131 extern std::vector<QLine> qlines;
132 extern std::vector<ELine> elines;
133 extern std::vector<KLine> pklines;
134 extern std::vector<GLine> pglines;
135 extern std::vector<ZLine> pzlines;
136 extern std::vector<QLine> pqlines;
137 extern std::vector<ELine> pelines;
139 /* Each server in the tree is represented by one class of
140 * type TreeServer. A locally connected TreeServer can
141 * have a class of type TreeSocket associated with it, for
142 * remote servers, the TreeSocket entry will be NULL.
143 * Each server also maintains a pointer to its parent
144 * (NULL if this server is ours, at the top of the tree)
145 * and a pointer to its "Route" (see the comments in the
146 * constructors below), and also a dynamic list of pointers
147 * to its children which can be iterated recursively
148 * if required. Creating or deleting objects of type
149 * TreeServer automatically maintains the hash_map of
150 * TreeServer items, deleting and inserting them as they
151 * are created and destroyed.
156 TreeServer* Parent; /* Parent entry */
157 TreeServer* Route; /* Route entry */
158 std::vector<TreeServer*> Children; /* List of child objects */
159 std::string ServerName; /* Server's name */
160 std::string ServerDesc; /* Server's description */
161 std::string VersionString; /* Version string or empty string */
162 int UserCount; /* Not used in this version */
163 int OperCount; /* Not used in this version */
164 TreeSocket* Socket; /* For directly connected servers this points at the socket object */
165 time_t NextPing; /* After this time, the server should be PINGed*/
166 bool LastPingWasGood; /* True if the server responded to the last PING with a PONG */
170 /* We don't use this constructor. Its a dummy, and won't cause any insertion
171 * of the TreeServer into the hash_map. See below for the two we DO use.
179 UserCount = OperCount = 0;
180 VersionString = Srv->GetVersion();
183 /* We use this constructor only to create the 'root' item, TreeRoot, which
184 * represents our own server. Therefore, it has no route, no parent, and
185 * no socket associated with it. Its version string is our own local version.
187 TreeServer(std::string Name, std::string Desc) : ServerName(Name), ServerDesc(Desc)
191 UserCount = OperCount = 0;
192 VersionString = Srv->GetVersion();
197 /* When we create a new server, we call this constructor to initialize it.
198 * This constructor initializes the server's Route and Parent, and sets up
199 * its ping counters so that it will be pinged one minute from now.
201 TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name), ServerDesc(Desc), Socket(Sock)
204 UserCount = OperCount = 0;
205 this->SetNextPingTime(time(NULL) + 60);
208 /* find the 'route' for this server (e.g. the one directly connected
209 * to the local server, which we can use to reach it)
211 * In the following example, consider we have just added a TreeServer
212 * class for server G on our network, of which we are server A.
213 * To route traffic to G (marked with a *) we must send the data to
214 * B (marked with a +) so this algorithm initializes the 'Route'
215 * value to point at whichever server traffic must be routed through
216 * to get here. If we were to try this algorithm with server B,
217 * the Route pointer would point at its own object ('this').
227 * We only run this algorithm when a server is created, as
228 * the routes remain constant while ever the server exists, and
229 * do not need to be re-calculated.
233 if (Route == TreeRoot)
239 while (this->Route->GetParent() != TreeRoot)
241 this->Route = Route->GetParent();
245 /* Because recursive code is slow and takes a lot of resources,
246 * we store two representations of the server tree. The first
247 * is a recursive structure where each server references its
248 * children and its parent, which is used for netbursts and
249 * netsplits to dump the whole dataset to the other server,
250 * and the second is used for very fast lookups when routing
251 * messages and is instead a hash_map, where each item can
252 * be referenced by its server name. The AddHashEntry()
253 * call below automatically inserts each TreeServer class
254 * into the hash_map as it is created. There is a similar
255 * maintainance call in the destructor to tidy up deleted
259 this->AddHashEntry();
262 /* This method is used to add the structure to the
263 * hash_map for linear searches. It is only called
264 * by the constructors.
268 server_hash::iterator iter;
269 iter = serverlist.find(this->ServerName);
270 if (iter == serverlist.end())
271 serverlist[this->ServerName] = this;
274 /* This method removes the reference to this object
275 * from the hash_map which is used for linear searches.
276 * It is only called by the default destructor.
280 server_hash::iterator iter;
281 iter = serverlist.find(this->ServerName);
282 if (iter != serverlist.end())
283 serverlist.erase(iter);
286 /* These accessors etc should be pretty self-
290 TreeServer* GetRoute()
295 std::string GetName()
297 return this->ServerName;
300 std::string GetDesc()
302 return this->ServerDesc;
305 std::string GetVersion()
307 return this->VersionString;
310 void SetNextPingTime(time_t t)
313 LastPingWasGood = false;
316 time_t NextPingTime()
318 return this->NextPing;
321 bool AnsweredLastPing()
323 return LastPingWasGood;
328 LastPingWasGood = true;
333 return this->UserCount;
338 return this->OperCount;
341 TreeSocket* GetSocket()
346 TreeServer* GetParent()
351 void SetVersion(std::string Version)
353 VersionString = Version;
356 unsigned int ChildCount()
358 return Children.size();
361 TreeServer* GetChild(unsigned int n)
363 if (n < Children.size())
365 /* Make sure they cant request
366 * an out-of-range object. After
367 * all we know what these programmer
368 * types are like *grin*.
378 void AddChild(TreeServer* Child)
380 Children.push_back(Child);
383 bool DelChild(TreeServer* Child)
385 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
396 /* Removes child nodes of this node, and of that node, etc etc.
397 * This is used during netsplits to automatically tidy up the
398 * server tree. It is slow, we don't use it for much else.
402 bool stillchildren = true;
403 while (stillchildren)
405 stillchildren = false;
406 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
408 TreeServer* s = (TreeServer*)*a;
412 stillchildren = true;
421 /* We'd better tidy up after ourselves, eh? */
422 this->DelHashEntry();
426 /* The Link class might as well be a struct,
427 * but this is C++ and we don't believe in structs (!).
428 * It holds the entire information of one <link>
429 * tag from the main config file. We maintain a list
430 * of them, and populate the list on rehash/load.
439 std::string SendPass;
440 std::string RecvPass;
441 unsigned long AutoConnect;
442 time_t NextConnectTime;
443 std::string EncryptionKey;
446 /* The usual stuff for inspircd modules,
447 * plus the vector of Link classes which we
448 * use to store the <link> tags from the config
452 std::vector<Link> LinkBlocks;
454 /* Yay for fast searches!
455 * This is hundreds of times faster than recursion
456 * or even scanning a linked list, especially when
457 * there are more than a few servers to deal with.
460 TreeServer* FindServer(std::string ServerName)
462 server_hash::iterator iter;
463 iter = serverlist.find(ServerName);
464 if (iter != serverlist.end())
474 /* Returns the locally connected server we must route a
475 * message through to reach server 'ServerName'. This
476 * only applies to one-to-one and not one-to-many routing.
477 * See the comments for the constructor of TreeServer
480 TreeServer* BestRouteTo(std::string ServerName)
482 if (ServerName.c_str() == TreeRoot->GetName())
484 TreeServer* Found = FindServer(ServerName);
487 return Found->GetRoute();
495 /* Find the first server matching a given glob mask.
496 * Theres no find-using-glob method of hash_map [awwww :-(]
497 * so instead, we iterate over the list using an iterator
498 * and match each one until we get a hit. Yes its slow,
501 TreeServer* FindServerMask(std::string ServerName)
503 for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
505 if (Srv->MatchText(i->first,ServerName))
511 /* A convenient wrapper that returns true if a server exists */
512 bool IsServer(std::string ServerName)
514 return (FindServer(ServerName) != NULL);
517 /* Every SERVER connection inbound or outbound is represented by
518 * an object of type TreeSocket.
519 * TreeSockets, being inherited from InspSocket, can be tied into
520 * the core socket engine, and we cn therefore receive activity events
521 * for them, just like activex objects on speed. (yes really, that
522 * is a technical term!) Each of these which relates to a locally
523 * connected server is assocated with it, by hooking it onto a
524 * TreeSocket class using its constructor. In this way, we can
525 * maintain a list of servers, some of which are directly connected,
526 * some of which are not.
529 class TreeSocket : public InspSocket
532 std::string in_buffer;
533 ServerState LinkState;
534 std::string InboundServerName;
535 std::string InboundDescription;
537 int num_lost_servers;
539 bool LastPingWasGood;
545 /* Because most of the I/O gubbins are encapsulated within
546 * InspSocket, we just call the superclass constructor for
547 * most of the action, and append a few of our own values
550 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
551 : InspSocket(host, port, listening, maxtime)
554 this->LinkState = LISTENER;
557 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName, std::string encryptionkey)
558 : InspSocket(host, port, listening, maxtime)
561 this->LinkState = CONNECTING;
562 InitAES(encryptionkey);
565 /* When a listening socket gives us a new file descriptor,
566 * we must associate it with a socket without creating a new
567 * connection. This constructor is used for this purpose.
569 TreeSocket(int newfd, char* ip, std::string encryptionkey)
570 : InspSocket(newfd, ip)
572 this->LinkState = WAIT_AUTH_1;
573 InitAES(encryptionkey);
576 void InitAES(std::string key)
582 // key must be 16, 24, 32 etc bytes (multiple of 8)
583 unsigned int keylength = key.length();
584 if (!(keylength == 16 || keylength == 24 || keylength == 32))
589 ctx->MakeKey(key.c_str(), "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0
590 \0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", keylength, keylength);
594 /* When an outbound connection finishes connecting, we receive
595 * this event, and must send our SERVER string to the other
596 * side. If the other side is happy, as outlined in the server
597 * to server docs on the inspircd.org site, the other side
598 * will then send back its own server string.
600 virtual bool OnConnected()
602 if (this->LinkState == CONNECTING)
604 Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
605 /* we do not need to change state here. */
606 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
608 if (x->Name == this->myhost)
610 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
611 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
616 /* There is a (remote) chance that between the /CONNECT and the connection
617 * being accepted, some muppet has removed the <link> block and rehashed.
618 * If that happens the connection hangs here until it's closed. Unlikely
619 * and rather harmless.
624 virtual void OnError(InspSocketError e)
626 /* We don't handle this method, because all our
627 * dirty work is done in OnClose() (see below)
628 * which is still called on error conditions too.
632 virtual int OnDisconnect()
634 /* For the same reason as above, we don't
635 * handle OnDisconnect()
640 /* Recursively send the server tree with distances as hops.
641 * This is used during network burst to inform the other server
642 * (and any of ITS servers too) of what servers we know about.
643 * If at any point any of these servers already exist on the other
644 * end, our connection may be terminated. The hopcounts given
645 * by this function are relative, this doesn't matter so long as
646 * they are all >1, as all the remote servers re-calculate them
647 * to be relative too, with themselves as hop 0.
649 void SendServers(TreeServer* Current, TreeServer* s, int hops)
652 for (unsigned int q = 0; q < Current->ChildCount(); q++)
654 TreeServer* recursive_server = Current->GetChild(q);
655 if (recursive_server != s)
657 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
658 this->WriteLine(command);
659 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
660 /* down to next level */
661 this->SendServers(recursive_server, s, hops+1);
666 /* This function forces this server to quit, removing this server
667 * and any users on it (and servers and users below that, etc etc).
668 * It's very slow and pretty clunky, but luckily unless your network
669 * is having a REAL bad hair day, this function shouldnt be called
670 * too many times a month ;-)
672 void SquitServer(TreeServer* Current, CullList* Goners)
674 /* recursively squit the servers attached to 'Current'.
675 * We're going backwards so we don't remove users
676 * while we still need them ;)
678 for (unsigned int q = 0; q < Current->ChildCount(); q++)
680 TreeServer* recursive_server = Current->GetChild(q);
681 this->SquitServer(recursive_server,Goners);
683 /* Now we've whacked the kids, whack self */
685 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
687 if (!strcasecmp(u->second->server,Current->GetName().c_str()))
689 std::string qreason = Current->GetName()+" "+std::string(Srv->GetServerName());
690 Goners->AddItem(u->second,qreason);
696 /* This is a wrapper function for SquitServer above, which
697 * does some validation first and passes on the SQUIT to all
698 * other remaining servers.
700 void Squit(TreeServer* Current,std::string reason)
704 std::deque<std::string> params;
705 params.push_back(Current->GetName());
706 params.push_back(":"+reason);
707 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
708 if (Current->GetParent() == TreeRoot)
710 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
714 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
716 num_lost_servers = 0;
718 CullList* Goners = new CullList();
719 SquitServer(Current, Goners);
722 Current->GetParent()->DelChild(Current);
725 WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
729 log(DEFAULT,"Squit from unknown server");
734 bool ForceMode(std::string source, std::deque<std::string> params)
736 userrec* who = new userrec;
737 who->fd = FD_MAGIC_NUMBER;
738 if (params.size() < 2)
741 for (unsigned int q = 0; q < params.size(); q++)
743 modelist[q] = (char*)params[q].c_str();
745 Srv->SendMode(modelist,params.size(),who);
746 DoOneToAllButSender(source,"FMODE",params,source);
752 bool ForceTopic(std::string source, std::deque<std::string> params)
754 if (params.size() != 4)
756 std::string channel = params[0];
757 time_t ts = atoi(params[1].c_str());
758 std::string setby = params[2];
759 std::string topic = params[3];
761 chanrec* c = Srv->FindChannel(channel);
764 if ((ts >= c->topicset) || (!*c->topic))
766 std::string oldtopic = c->topic;
767 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
768 strlcpy(c->setby,setby.c_str(),NICKMAX);
770 /* if the topic text is the same as the current topic,
771 * dont bother to send the TOPIC command out, just silently
772 * update the set time and set nick.
774 if (oldtopic != topic)
775 WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
780 /* all done, send it on its way */
781 params[3] = ":" + params[3];
782 DoOneToAllButSender(source,"FTOPIC",params,source);
787 /* FJOIN, similar to unreal SJOIN */
788 bool ForceJoin(std::string source, std::deque<std::string> params)
790 if (params.size() < 3)
794 char modestring[MAXBUF];
795 char* mode_users[127];
796 mode_users[0] = first;
797 mode_users[1] = modestring;
798 strcpy(mode_users[1],"+");
799 unsigned int modectr = 2;
802 std::string channel = params[0];
803 time_t TS = atoi(params[1].c_str());
806 chanrec* chan = Srv->FindChannel(channel);
811 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
813 /* default is a high value, which if we dont have this
814 * channel will let the other side apply their modes.
816 time_t ourTS = time(NULL)+600;
817 chanrec* us = Srv->FindChannel(channel);
823 log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
825 /* do this first, so our mode reversals are correctly received by other servers
826 * if there is a TS collision.
828 DoOneToAllButSender(source,"FJOIN",params,source);
830 for (unsigned int usernum = 2; usernum < params.size(); usernum++)
832 /* process one channel at a time, applying modes. */
833 char* usr = (char*)params[usernum].c_str();
834 char permissions = *usr;
839 mode_users[modectr++] = usr;
840 strlcat(modestring,"o",MAXBUF);
844 mode_users[modectr++] = usr;
845 strlcat(modestring,"h",MAXBUF);
849 mode_users[modectr++] = usr;
850 strlcat(modestring,"v",MAXBUF);
853 who = Srv->FindNick(usr);
856 Srv->JoinUserToChannel(who,channel,key);
857 if (modectr >= (MAXMODES-1))
859 /* theres a mode for this user. push them onto the mode queue, and flush it
860 * if there are more than MAXMODES to go.
862 if ((ourTS >= TS) || (Srv->IsUlined(who->server)))
864 /* We also always let u-lined clients win, no matter what the TS value */
865 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
866 Srv->SendMode(mode_users,modectr,who);
870 log(DEBUG,"Their channel newer than ours, bouncing their modes");
872 std::deque<std::string> params;
873 /* modes are now being UNSET... */
874 *mode_users[1] = '-';
875 for (unsigned int x = 0; x < modectr; x++)
877 params.push_back(mode_users[x]);
879 // tell everyone to bounce the modes. bad modes, bad!
880 DoOneToMany(Srv->GetServerName(),"FMODE",params);
882 strcpy(mode_users[1],"+");
887 /* there werent enough modes built up to flush it during FJOIN,
888 * or, there are a number left over. flush them out.
890 if ((modectr > 2) && (who))
894 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
895 Srv->SendMode(mode_users,modectr,who);
899 log(DEBUG,"Their channel newer than ours, bouncing their modes");
900 std::deque<std::string> params;
901 *mode_users[1] = '-';
902 for (unsigned int x = 0; x < modectr; x++)
904 params.push_back(mode_users[x]);
906 DoOneToMany(Srv->GetServerName(),"FMODE",params);
913 bool IntroduceClient(std::string source, std::deque<std::string> params)
915 if (params.size() < 8)
917 // NICK age nick host dhost ident +modes ip :gecos
919 std::string nick = params[1];
920 std::string host = params[2];
921 std::string dhost = params[3];
922 std::string ident = params[4];
923 time_t age = atoi(params[0].c_str());
924 std::string modes = params[5];
925 while (*(modes.c_str()) == '+')
927 char* m = (char*)modes.c_str();
931 std::string ip = params[6];
932 std::string gecos = params[7];
933 char* tempnick = (char*)nick.c_str();
934 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
936 user_hash::iterator iter;
937 iter = clientlist.find(tempnick);
938 if (iter != clientlist.end())
941 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);
942 this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
946 clientlist[tempnick] = new userrec();
947 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
948 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
949 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
950 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
951 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
952 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
953 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
954 clientlist[tempnick]->registered = 7;
955 clientlist[tempnick]->signon = age;
956 strlcpy(clientlist[tempnick]->modes, modes.c_str(),53);
957 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
962 for (int i = 0; i < MAXCHANS; i++)
963 clientlist[tempnick]->chans.push_back(a);
967 WriteOpers("*** Client connecting at %s: %s!%s@%s [%s]",clientlist[tempnick]->server,clientlist[tempnick]->nick,clientlist[tempnick]->ident,clientlist[tempnick]->host,clientlist[tempnick]->ip);
969 params[7] = ":" + params[7];
970 DoOneToAllButSender(source,"NICK",params,source);
974 /* Send one or more FJOINs for a channel of users.
975 * If the length of a single line is more than 480-NICKMAX
976 * in length, it is split over multiple lines.
978 void SendFJoins(TreeServer* Current, chanrec* c)
980 log(DEBUG,"Sending FJOINs to other server for %s",c->name);
982 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
983 std::vector<char*> *ulist = c->GetUsers();
984 for (unsigned int i = 0; i < ulist->size(); i++)
986 char* o = (*ulist)[i];
987 userrec* otheruser = (userrec*)o;
988 strlcat(list," ",MAXBUF);
989 strlcat(list,cmode(otheruser,c),MAXBUF);
990 strlcat(list,otheruser->nick,MAXBUF);
991 if (strlen(list)>(480-NICKMAX))
993 log(DEBUG,"FJOIN line wrapped");
994 this->WriteLine(list);
995 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
998 if (list[strlen(list)-1] != ':')
1000 log(DEBUG,"Final FJOIN line");
1001 this->WriteLine(list);
1005 /* Send G, Q, Z and E lines */
1006 void SendXLines(TreeServer* Current)
1009 /* Yes, these arent too nice looking, but they get the job done */
1010 for (std::vector<ZLine>::iterator i = zlines.begin(); i != zlines.end(); i++)
1012 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);
1013 this->WriteLine(data);
1015 for (std::vector<QLine>::iterator i = qlines.begin(); i != qlines.end(); i++)
1017 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);
1018 this->WriteLine(data);
1020 for (std::vector<GLine>::iterator i = glines.begin(); i != glines.end(); i++)
1022 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);
1023 this->WriteLine(data);
1025 for (std::vector<ELine>::iterator i = elines.begin(); i != elines.end(); i++)
1027 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);
1028 this->WriteLine(data);
1030 for (std::vector<ZLine>::iterator i = pzlines.begin(); i != pzlines.end(); i++)
1032 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);
1033 this->WriteLine(data);
1035 for (std::vector<QLine>::iterator i = pqlines.begin(); i != pqlines.end(); i++)
1037 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);
1038 this->WriteLine(data);
1040 for (std::vector<GLine>::iterator i = pglines.begin(); i != pglines.end(); i++)
1042 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);
1043 this->WriteLine(data);
1045 for (std::vector<ELine>::iterator i = pelines.begin(); i != pelines.end(); i++)
1047 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);
1048 this->WriteLine(data);
1052 /* Send channel modes and topics */
1053 void SendChannelModes(TreeServer* Current)
1056 std::deque<std::string> list;
1057 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
1059 SendFJoins(Current, c->second);
1060 snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
1061 this->WriteLine(data);
1062 if (*c->second->topic)
1064 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);
1065 this->WriteLine(data);
1067 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
1069 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
1070 this->WriteLine(data);
1072 FOREACH_MOD OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this);
1074 c->second->GetExtList(list);
1075 for (unsigned int j = 0; j < list.size(); j++)
1077 FOREACH_MOD OnSyncChannelMetaData(c->second,(Module*)TreeProtocolModule,(void*)this,list[j]);
1082 /* send all users and their oper state/modes */
1083 void SendUsers(TreeServer* Current)
1086 std::deque<std::string> list;
1087 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
1089 if (u->second->registered == 7)
1091 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);
1092 this->WriteLine(data);
1093 if (strchr(u->second->modes,'o'))
1095 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
1097 FOREACH_MOD OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this);
1099 u->second->GetExtList(list);
1100 for (unsigned int j = 0; j < list.size(); j++)
1102 FOREACH_MOD OnSyncUserMetaData(u->second,(Module*)TreeProtocolModule,(void*)this,list[j]);
1108 /* This function is called when we want to send a netburst to a local
1109 * server. There is a set order we must do this, because for example
1110 * users require their servers to exist, and channels require their
1111 * users to exist. You get the idea.
1113 void DoBurst(TreeServer* s)
1115 Srv->SendOpers("*** Bursting to \2"+s->GetName()+"\2.");
1116 this->WriteLine("BURST");
1117 /* send our version string */
1118 this->WriteLine(":"+Srv->GetServerName()+" VERSION :"+Srv->GetVersion());
1119 /* Send server tree */
1120 this->SendServers(TreeRoot,s,1);
1121 /* Send users and their oper status */
1123 /* Send everything else (channel modes, xlines etc) */
1124 this->SendChannelModes(s);
1125 this->SendXLines(s);
1126 this->WriteLine("ENDBURST");
1127 Srv->SendOpers("*** Finished bursting to \2"+s->GetName()+"\2.");
1130 /* This function is called when we receive data from a remote
1131 * server. We buffer the data in a std::string (it doesnt stay
1132 * there for long), reading using InspSocket::Read() which can
1133 * read up to 16 kilobytes in one operation.
1135 * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
1136 * THE SOCKET OBJECT FOR US.
1138 virtual bool OnDataReady()
1140 char* data = this->Read();
1143 Srv->Log(DEBUG,"m_spanningtree: READ");
1144 this->in_buffer += data;
1145 /* While there is at least one new line in the buffer,
1146 * do something useful (we hope!) with it.
1148 while (in_buffer.find("\n") != std::string::npos)
1150 char* line = (char*)in_buffer.c_str();
1151 std::string ret = "";
1152 while ((*line != '\n') && (strlen(line)))
1157 if ((*line == '\n') || (*line == '\r'))
1160 /* Process this one, abort if it
1161 * didnt return true.
1167 int nbytes = from64tobits(out, ret.c_str(), 1024);
1168 log(DEBUG,"m_spanningtree: decrypt %d bytes",nbytes);
1169 ctx->Decrypt(out, result, nbytes, AES::ECB);
1172 if (!this->ProcessLine(ret))
1178 return (data != NULL);
1181 int WriteLine(std::string line)
1183 log(DEBUG,"OUT: %s",line.c_str());
1187 char* result64[1024];
1188 while (line.length() % this->keylength != 0)
1190 // pad it to be a multiple of the key length
1193 ctx->Encrypt(line.c_str(), result, line.length(), AES::ECB);
1194 to64frombits(result64, result, line.length());
1196 log(DEBUG,"Encrypted: %s",line.c_str());
1197 //int from64tobits(char *out, const char *in, int maxlen);
1199 return this->Write(line + "\r\n");
1202 /* Handle ERROR command */
1203 bool Error(std::deque<std::string> params)
1205 if (params.size() < 1)
1207 std::string Errmsg = params[0];
1208 std::string SName = myhost;
1209 if (InboundServerName != "")
1211 SName = InboundServerName;
1213 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
1214 /* we will return false to cause the socket to close.
1219 /* Because the core won't let users or even SERVERS set +o,
1220 * we use the OPERTYPE command to do this.
1222 bool OperType(std::string prefix, std::deque<std::string> ¶ms)
1224 if (params.size() != 1)
1226 std::string opertype = params[0];
1227 userrec* u = Srv->FindNick(prefix);
1230 strlcpy(u->oper,opertype.c_str(),NICKMAX);
1231 if (!strchr(u->modes,'o'))
1233 strcat(u->modes,"o");
1235 DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
1240 /* Because Andy insists that services-compatible servers must
1241 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
1243 bool ForceNick(std::string prefix, std::deque<std::string> ¶ms)
1245 if (params.size() < 3)
1247 userrec* u = Srv->FindNick(params[0]);
1250 Srv->ChangeUserNick(u,params[1]);
1251 u->age = atoi(params[2].c_str());
1252 DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
1257 bool ServiceJoin(std::string prefix, std::deque<std::string> ¶ms)
1259 if (params.size() < 2)
1261 userrec* u = Srv->FindNick(params[0]);
1264 Srv->JoinUserToChannel(u,params[1],"");
1265 DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
1270 bool RemoteRehash(std::string prefix, std::deque<std::string> ¶ms)
1272 if (params.size() < 1)
1274 std::string servermask = params[0];
1275 if (Srv->MatchText(Srv->GetServerName(),servermask))
1277 Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
1278 Srv->RehashServer();
1279 ReadConfiguration(false);
1281 DoOneToAllButSender(prefix,"REHASH",params,prefix);
1285 bool RemoteKill(std::string prefix, std::deque<std::string> ¶ms)
1287 if (params.size() != 2)
1289 std::string nick = params[0];
1290 userrec* u = Srv->FindNick(prefix);
1291 userrec* who = Srv->FindNick(nick);
1294 /* Prepend kill source, if we don't have one */
1295 std::string sourceserv = prefix;
1298 sourceserv = u->server;
1300 if (*(params[1].c_str()) != '[')
1302 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
1304 std::string reason = params[1];
1305 params[1] = ":" + params[1];
1306 DoOneToAllButSender(prefix,"KILL",params,sourceserv);
1307 Srv->QuitUser(who,reason);
1312 bool LocalPong(std::string prefix, std::deque<std::string> ¶ms)
1314 if (params.size() < 1)
1316 TreeServer* ServerSource = FindServer(prefix);
1319 ServerSource->SetPingFlag();
1324 bool MetaData(std::string prefix, std::deque<std::string> ¶ms)
1326 if (params.size() < 3)
1328 TreeServer* ServerSource = FindServer(prefix);
1331 if (*(params[0].c_str()) == '#')
1333 chanrec* c = Srv->FindChannel(params[0]);
1336 FOREACH_MOD OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]);
1341 userrec* u = Srv->FindNick(params[0]);
1344 FOREACH_MOD OnDecodeMetaData(TYPE_USER,u,params[1],params[2]);
1348 params[2] = ":" + params[2];
1349 DoOneToAllButSender(prefix,"METADATA",params,prefix);
1353 bool ServerVersion(std::string prefix, std::deque<std::string> ¶ms)
1355 if (params.size() < 1)
1357 TreeServer* ServerSource = FindServer(prefix);
1360 ServerSource->SetVersion(params[0]);
1362 params[0] = ":" + params[0];
1363 DoOneToAllButSender(prefix,"VERSION",params,prefix);
1367 bool ChangeHost(std::string prefix, std::deque<std::string> ¶ms)
1369 if (params.size() < 1)
1371 userrec* u = Srv->FindNick(prefix);
1374 Srv->ChangeHost(u,params[0]);
1375 DoOneToAllButSender(prefix,"FHOST",params,u->server);
1380 bool AddLine(std::string prefix, std::deque<std::string> ¶ms)
1382 if (params.size() < 6)
1384 std::string linetype = params[0]; /* Z, Q, E, G, K */
1385 std::string mask = params[1]; /* Line type dependent */
1386 std::string source = params[2]; /* may not be online or may be a server */
1387 std::string settime = params[3]; /* EPOCH time set */
1388 std::string duration = params[4]; /* Duration secs */
1389 std::string reason = params[5];
1391 switch (*(linetype.c_str()))
1394 add_zline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1395 zline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1398 add_qline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1399 qline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1402 add_eline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1403 eline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1406 add_gline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1407 gline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1410 add_kline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1413 /* Just in case... */
1414 Srv->SendOpers("*** \2WARNING\2: Invalid xline type '"+linetype+"' sent by server "+prefix+", ignored!");
1417 /* Send it on its way */
1418 params[5] = ":" + params[5];
1419 DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
1423 bool ChangeName(std::string prefix, std::deque<std::string> ¶ms)
1425 if (params.size() < 1)
1427 userrec* u = Srv->FindNick(prefix);
1430 Srv->ChangeGECOS(u,params[0]);
1431 params[0] = ":" + params[0];
1432 DoOneToAllButSender(prefix,"FNAME",params,u->server);
1437 bool Whois(std::string prefix, std::deque<std::string> ¶ms)
1439 if (params.size() < 1)
1441 log(DEBUG,"In IDLE command");
1442 userrec* u = Srv->FindNick(prefix);
1445 log(DEBUG,"USER EXISTS: %s",u->nick);
1446 // an incoming request
1447 if (params.size() == 1)
1449 userrec* x = Srv->FindNick(params[0]);
1452 userrec* x = Srv->FindNick(params[0]);
1453 log(DEBUG,"Got IDLE");
1454 char signon[MAXBUF];
1456 log(DEBUG,"Sending back IDLE 3");
1457 snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
1458 snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-time(NULL)));
1459 std::deque<std::string> par;
1460 par.push_back(prefix);
1461 par.push_back(signon);
1462 par.push_back(idle);
1463 // ours, we're done, pass it BACK
1464 DoOneToOne(params[0],"IDLE",par,u->server);
1468 // not ours pass it on
1469 DoOneToOne(prefix,"IDLE",params,x->server);
1472 else if (params.size() == 3)
1474 std::string who_did_the_whois = params[0];
1475 userrec* who_to_send_to = Srv->FindNick(who_did_the_whois);
1476 if (who_to_send_to->fd > -1)
1478 log(DEBUG,"Got final IDLE");
1479 // an incoming reply to a whois we sent out
1480 std::string nick_whoised = prefix;
1481 unsigned long signon = atoi(params[1].c_str());
1482 unsigned long idle = atoi(params[2].c_str());
1483 if ((who_to_send_to) && (who_to_send_to->fd > -1))
1484 do_whois(who_to_send_to,u,signon,idle,(char*)nick_whoised.c_str());
1488 // not ours, pass it on
1489 DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
1496 bool LocalPing(std::string prefix, std::deque<std::string> ¶ms)
1498 if (params.size() < 1)
1500 std::string stufftobounce = params[0];
1501 this->WriteLine(":"+Srv->GetServerName()+" PONG "+stufftobounce);
1505 bool RemoteServer(std::string prefix, std::deque<std::string> ¶ms)
1507 if (params.size() < 4)
1509 std::string servername = params[0];
1510 std::string password = params[1];
1511 // hopcount is not used for a remote server, we calculate this ourselves
1512 std::string description = params[3];
1513 TreeServer* ParentOfThis = FindServer(prefix);
1516 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
1519 TreeServer* CheckDupe = FindServer(servername);
1522 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1525 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
1526 ParentOfThis->AddChild(Node);
1527 params[3] = ":" + params[3];
1528 DoOneToAllButSender(prefix,"SERVER",params,prefix);
1529 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
1533 bool Outbound_Reply_Server(std::deque<std::string> ¶ms)
1535 if (params.size() < 4)
1537 std::string servername = params[0];
1538 std::string password = params[1];
1539 int hops = atoi(params[2].c_str());
1542 this->WriteLine("ERROR :Server too far away for authentication");
1545 std::string description = params[3];
1546 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1548 if ((x->Name == servername) && (x->RecvPass == password))
1550 TreeServer* CheckDupe = FindServer(servername);
1553 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1556 // Begin the sync here. this kickstarts the
1557 // other side, waiting in WAIT_AUTH_2 state,
1558 // into starting their burst, as it shows
1559 // that we're happy.
1560 this->LinkState = CONNECTED;
1561 // we should add the details of this server now
1562 // to the servers tree, as a child of the root
1564 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
1565 TreeRoot->AddChild(Node);
1566 params[3] = ":" + params[3];
1567 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
1568 this->bursting = true;
1569 this->DoBurst(Node);
1573 this->WriteLine("ERROR :Invalid credentials");
1577 bool Inbound_Server(std::deque<std::string> ¶ms)
1579 if (params.size() < 4)
1581 std::string servername = params[0];
1582 std::string password = params[1];
1583 int hops = atoi(params[2].c_str());
1586 this->WriteLine("ERROR :Server too far away for authentication");
1589 std::string description = params[3];
1590 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1592 if ((x->Name == servername) && (x->RecvPass == password))
1594 TreeServer* CheckDupe = FindServer(servername);
1597 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1600 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
1601 this->InboundServerName = servername;
1602 this->InboundDescription = description;
1603 // this is good. Send our details: Our server name and description and hopcount of 0,
1604 // along with the sendpass from this block.
1605 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
1606 // move to the next state, we are now waiting for THEM.
1607 this->LinkState = WAIT_AUTH_2;
1611 this->WriteLine("ERROR :Invalid credentials");
1615 void Split(std::string line, bool stripcolon, std::deque<std::string> &n)
1617 if (!strchr(line.c_str(),' '))
1622 std::stringstream s(line);
1623 std::string param = "";
1642 if ((param == ":") && (item > 0))
1665 bool ProcessLine(std::string line)
1667 char* l = (char*)line.c_str();
1668 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
1669 l[strlen(l)-1] = '\0';
1673 Srv->Log(DEBUG,"IN: "+line);
1674 std::deque<std::string> params;
1675 this->Split(line,true,params);
1676 std::string command = "";
1677 std::string prefix = "";
1678 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
1681 command = params[1];
1682 char* pref = (char*)prefix.c_str();
1690 command = params[0];
1694 switch (this->LinkState)
1699 // Waiting for SERVER command from remote server. Server initiating
1700 // the connection sends the first SERVER command, listening server
1701 // replies with theirs if its happy, then if the initiator is happy,
1702 // it starts to send its net sync, which starts the merge, otherwise
1703 // it sends an ERROR.
1704 if (command == "SERVER")
1706 return this->Inbound_Server(params);
1708 else if (command == "ERROR")
1710 return this->Error(params);
1714 // Waiting for start of other side's netmerge to say they liked our
1716 if (command == "SERVER")
1718 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1722 else if (command == "BURST")
1724 this->LinkState = CONNECTED;
1725 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
1726 TreeRoot->AddChild(Node);
1728 params.push_back(InboundServerName);
1729 params.push_back("*");
1730 params.push_back("1");
1731 params.push_back(":"+InboundDescription);
1732 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
1733 this->bursting = true;
1734 this->DoBurst(Node);
1736 else if (command == "ERROR")
1738 return this->Error(params);
1743 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
1747 if (command == "SERVER")
1749 // another server we connected to, which was in WAIT_AUTH_1 state,
1750 // has just sent us their credentials. If we get this far, theyre
1751 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1752 // if we're happy with this, we should send our netburst which
1753 // kickstarts the merge.
1754 return this->Outbound_Reply_Server(params);
1756 else if (command == "ERROR")
1758 return this->Error(params);
1762 // This is the 'authenticated' state, when all passwords
1763 // have been exchanged and anything past this point is taken
1768 std::string direction = prefix;
1769 userrec* t = Srv->FindNick(prefix);
1772 direction = t->server;
1774 TreeServer* route_back_again = BestRouteTo(direction);
1775 if ((!route_back_again) || (route_back_again->GetSocket() != this))
1777 if (route_back_again)
1779 WriteOpers("Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
1783 WriteOpers("Protocol violation: Invalid source '%s' in command '%s' from connection '%s'",direction.c_str(),line.c_str(),this->GetName().c_str());
1790 if (command == "SVSMODE")
1792 /* Services expects us to implement
1793 * SVSMODE. In inspircd its the same as
1798 std::string target = "";
1799 /* Yes, know, this is a mess. Its reasonably fast though as we're
1800 * working with std::string here.
1802 if ((command == "NICK") && (params.size() > 1))
1804 return this->IntroduceClient(prefix,params);
1806 else if (command == "FJOIN")
1808 return this->ForceJoin(prefix,params);
1810 else if (command == "SERVER")
1812 return this->RemoteServer(prefix,params);
1814 else if (command == "ERROR")
1816 return this->Error(params);
1818 else if (command == "OPERTYPE")
1820 return this->OperType(prefix,params);
1822 else if (command == "FMODE")
1824 return this->ForceMode(prefix,params);
1826 else if (command == "KILL")
1828 return this->RemoteKill(prefix,params);
1830 else if (command == "FTOPIC")
1832 return this->ForceTopic(prefix,params);
1834 else if (command == "REHASH")
1836 return this->RemoteRehash(prefix,params);
1838 else if (command == "METADATA")
1840 return this->MetaData(prefix,params);
1842 else if (command == "PING")
1844 return this->LocalPing(prefix,params);
1846 else if (command == "PONG")
1848 return this->LocalPong(prefix,params);
1850 else if (command == "VERSION")
1852 return this->ServerVersion(prefix,params);
1854 else if (command == "FHOST")
1856 return this->ChangeHost(prefix,params);
1858 else if (command == "FNAME")
1860 return this->ChangeName(prefix,params);
1862 else if (command == "ADDLINE")
1864 return this->AddLine(prefix,params);
1866 else if (command == "SVSNICK")
1870 prefix = this->GetName();
1872 return this->ForceNick(prefix,params);
1874 else if (command == "IDLE")
1876 return this->Whois(prefix,params);
1878 else if (command == "SVSJOIN")
1882 prefix = this->GetName();
1884 return this->ServiceJoin(prefix,params);
1886 else if (command == "SQUIT")
1888 if (params.size() == 2)
1890 this->Squit(FindServer(params[0]),params[1]);
1894 else if (command == "ENDBURST")
1896 this->bursting = false;
1901 // not a special inter-server command.
1902 // Emulate the actual user doing the command,
1903 // this saves us having a huge ugly parser.
1904 userrec* who = Srv->FindNick(prefix);
1905 std::string sourceserv = this->myhost;
1906 if (this->InboundServerName != "")
1908 sourceserv = this->InboundServerName;
1913 target = who->server;
1914 char* strparams[127];
1915 for (unsigned int q = 0; q < params.size(); q++)
1917 strparams[q] = (char*)params[q].c_str();
1919 Srv->CallCommandHandler(command, strparams, params.size(), who);
1923 // its not a user. Its either a server, or somethings screwed up.
1924 if (IsServer(prefix))
1926 target = Srv->GetServerName();
1930 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
1934 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1943 virtual std::string GetName()
1945 std::string sourceserv = this->myhost;
1946 if (this->InboundServerName != "")
1948 sourceserv = this->InboundServerName;
1953 virtual void OnTimeout()
1955 if (this->LinkState == CONNECTING)
1957 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
1961 virtual void OnClose()
1963 // Connection closed.
1964 // If the connection is fully up (state CONNECTED)
1965 // then propogate a netsplit to all peers.
1966 std::string quitserver = this->myhost;
1967 if (this->InboundServerName != "")
1969 quitserver = this->InboundServerName;
1971 TreeServer* s = FindServer(quitserver);
1974 Squit(s,"Remote host closed the connection");
1978 virtual int OnIncomingConnection(int newsock, char* ip)
1980 TreeSocket* s = new TreeSocket(newsock, ip);
1986 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
1988 for (unsigned int c = 0; c < list.size(); c++)
1990 if (list[c] == server)
1995 list.push_back(server);
1998 // returns a list of DIRECT servernames for a specific channel
1999 void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
2001 std::vector<char*> *ulist = c->GetUsers();
2002 unsigned int ucount = ulist->size();
2003 for (unsigned int i = 0; i < ucount; i++)
2005 char* o = (*ulist)[i];
2006 userrec* otheruser = (userrec*)o;
2007 if (otheruser->fd < 0)
2009 TreeServer* best = BestRouteTo(otheruser->server);
2011 AddThisServer(best,list);
2017 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, std::string command, std::deque<std::string> ¶ms)
2019 TreeServer* omitroute = BestRouteTo(omit);
2020 if ((command == "NOTICE") || (command == "PRIVMSG"))
2022 if ((params.size() >= 2) && (*(params[0].c_str()) != '$'))
2024 if (*(params[0].c_str()) != '#')
2026 // special routing for private messages/notices
2027 userrec* d = Srv->FindNick(params[0]);
2030 std::deque<std::string> par;
2031 par.push_back(params[0]);
2032 par.push_back(":"+params[1]);
2033 DoOneToOne(prefix,command,par,d->server);
2039 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
2040 chanrec* c = Srv->FindChannel(params[0]);
2043 std::deque<TreeServer*> list;
2044 GetListOfServersForChannel(c,list);
2045 log(DEBUG,"Got a list of %d servers",list.size());
2046 unsigned int lsize = list.size();
2047 for (unsigned int i = 0; i < lsize; i++)
2049 TreeSocket* Sock = list[i]->GetSocket();
2050 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
2052 log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
2053 Sock->WriteLine(data);
2061 unsigned int items = TreeRoot->ChildCount();
2062 for (unsigned int x = 0; x < items; x++)
2064 TreeServer* Route = TreeRoot->GetChild(x);
2065 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
2067 TreeSocket* Sock = Route->GetSocket();
2068 Sock->WriteLine(data);
2074 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string omit)
2076 TreeServer* omitroute = BestRouteTo(omit);
2077 std::string FullLine = ":" + prefix + " " + command;
2078 unsigned int words = params.size();
2079 for (unsigned int x = 0; x < words; x++)
2081 FullLine = FullLine + " " + params[x];
2083 unsigned int items = TreeRoot->ChildCount();
2084 for (unsigned int x = 0; x < items; x++)
2086 TreeServer* Route = TreeRoot->GetChild(x);
2087 // Send the line IF:
2088 // The route has a socket (its a direct connection)
2089 // The route isnt the one to be omitted
2090 // The route isnt the path to the one to be omitted
2091 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
2093 TreeSocket* Sock = Route->GetSocket();
2094 Sock->WriteLine(FullLine);
2100 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> ¶ms)
2102 std::string FullLine = ":" + prefix + " " + command;
2103 unsigned int words = params.size();
2104 for (unsigned int x = 0; x < words; x++)
2106 FullLine = FullLine + " " + params[x];
2108 unsigned int items = TreeRoot->ChildCount();
2109 for (unsigned int x = 0; x < items; x++)
2111 TreeServer* Route = TreeRoot->GetChild(x);
2112 if (Route->GetSocket())
2114 TreeSocket* Sock = Route->GetSocket();
2115 Sock->WriteLine(FullLine);
2121 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string target)
2123 TreeServer* Route = BestRouteTo(target);
2126 std::string FullLine = ":" + prefix + " " + command;
2127 unsigned int words = params.size();
2128 for (unsigned int x = 0; x < words; x++)
2130 FullLine = FullLine + " " + params[x];
2132 if (Route->GetSocket())
2134 TreeSocket* Sock = Route->GetSocket();
2135 Sock->WriteLine(FullLine);
2145 std::vector<TreeSocket*> Bindings;
2147 void ReadConfiguration(bool rebind)
2149 Conf = new ConfigReader;
2152 for (int j =0; j < Conf->Enumerate("bind"); j++)
2154 std::string Type = Conf->ReadValue("bind","type",j);
2155 std::string IP = Conf->ReadValue("bind","address",j);
2156 long Port = Conf->ReadInteger("bind","port",j,true);
2157 if (Type == "servers")
2163 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
2164 if (listener->GetState() == I_LISTENING)
2166 Srv->AddSocket(listener);
2167 Bindings.push_back(listener);
2171 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
2179 for (int j =0; j < Conf->Enumerate("link"); j++)
2182 L.Name = Conf->ReadValue("link","name",j);
2183 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
2184 L.Port = Conf->ReadInteger("link","port",j,true);
2185 L.SendPass = Conf->ReadValue("link","sendpass",j);
2186 L.RecvPass = Conf->ReadValue("link","recvpass",j);
2187 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
2188 L.EncryptionKey = Conf->ReadValue("link","encryptionkey",j);
2189 L.NextConnectTime = time(NULL) + L.AutoConnect;
2190 /* Bugfix by brain, do not allow people to enter bad configurations */
2191 if ((L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
2193 LinkBlocks.push_back(L);
2194 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
2198 log(DEFAULT,"m_spanningtree: Invalid configuration for server '%s', ignored!",L.Name.c_str());
2205 class ModuleSpanningTree : public Module
2207 std::vector<TreeSocket*> Bindings;
2213 ModuleSpanningTree(Server* Me)
2214 : Module::Module(Me)
2219 // Create the root of the tree
2220 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
2222 ReadConfiguration(true);
2225 void ShowLinks(TreeServer* Current, userrec* user, int hops)
2227 std::string Parent = TreeRoot->GetName();
2228 if (Current->GetParent())
2230 Parent = Current->GetParent()->GetName();
2232 for (unsigned int q = 0; q < Current->ChildCount(); q++)
2234 ShowLinks(Current->GetChild(q),user,hops+1);
2236 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
2239 int CountLocalServs()
2241 return TreeRoot->ChildCount();
2246 return serverlist.size();
2249 void HandleLinks(char** parameters, int pcnt, userrec* user)
2251 ShowLinks(TreeRoot,user,0);
2252 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
2256 void HandleLusers(char** parameters, int pcnt, userrec* user)
2258 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),this->CountServs());
2259 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
2260 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
2261 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
2262 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
2266 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
2268 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
2272 for (int t = 0; t < depth; t++)
2274 matrix[line][t] = ' ';
2276 strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
2278 for (unsigned int q = 0; q < Current->ChildCount(); q++)
2280 ShowMap(Current->GetChild(q),user,depth+2,matrix);
2285 // Ok, prepare to be confused.
2286 // After much mulling over how to approach this, it struck me that
2287 // the 'usual' way of doing a /MAP isnt the best way. Instead of
2288 // keeping track of a ton of ascii characters, and line by line
2289 // under recursion working out where to place them using multiplications
2290 // and divisons, we instead render the map onto a backplane of characters
2291 // (a character matrix), then draw the branches as a series of "L" shapes
2292 // from the nodes. This is not only friendlier on CPU it uses less stack.
2294 void HandleMap(char** parameters, int pcnt, userrec* user)
2296 // This array represents a virtual screen which we will
2297 // "scratch" draw to, as the console device of an irc
2298 // client does not provide for a proper terminal.
2299 char matrix[128][80];
2300 for (unsigned int t = 0; t < 128; t++)
2302 matrix[t][0] = '\0';
2305 // The only recursive bit is called here.
2306 ShowMap(TreeRoot,user,0,matrix);
2307 // Process each line one by one. The algorithm has a limit of
2308 // 128 servers (which is far more than a spanning tree should have
2309 // anyway, so we're ok). This limit can be raised simply by making
2310 // the character matrix deeper, 128 rows taking 10k of memory.
2311 for (int l = 1; l < line; l++)
2313 // scan across the line looking for the start of the
2314 // servername (the recursive part of the algorithm has placed
2315 // the servers at indented positions depending on what they
2317 int first_nonspace = 0;
2318 while (matrix[l][first_nonspace] == ' ')
2323 // Draw the `- (corner) section: this may be overwritten by
2324 // another L shape passing along the same vertical pane, becoming
2325 // a |- (branch) section instead.
2326 matrix[l][first_nonspace] = '-';
2327 matrix[l][first_nonspace-1] = '`';
2329 // Draw upwards until we hit the parent server, causing possibly
2330 // other corners (`-) to become branches (|-)
2331 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
2333 matrix[l2][first_nonspace-1] = '|';
2337 // dump the whole lot to the user. This is the easy bit, honest.
2338 for (int t = 0; t < line; t++)
2340 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
2342 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
2346 int HandleSquit(char** parameters, int pcnt, userrec* user)
2348 TreeServer* s = FindServerMask(parameters[0]);
2351 TreeSocket* sock = s->GetSocket();
2354 WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
2355 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
2360 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
2365 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
2370 int HandleRemoteWhois(char** parameters, int pcnt, userrec* user)
2372 if ((user->fd > -1) && (pcnt > 1))
2374 userrec* remote = Srv->FindNick(parameters[1]);
2375 if ((remote) && (remote->fd < 0))
2377 std::deque<std::string> params;
2378 params.push_back(parameters[1]);
2379 DoOneToOne(user->nick,"IDLE",params,remote->server);
2384 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
2385 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
2392 void DoPingChecks(time_t curtime)
2394 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
2396 TreeServer* serv = TreeRoot->GetChild(j);
2397 TreeSocket* sock = serv->GetSocket();
2400 if (curtime >= serv->NextPingTime())
2402 if (serv->AnsweredLastPing())
2404 sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
2405 serv->SetNextPingTime(curtime + 60);
2409 // they didnt answer, boot them
2410 WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
2411 sock->Squit(serv,"Ping timeout");
2420 void AutoConnectServers(time_t curtime)
2422 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2424 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
2426 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
2427 x->NextConnectTime = curtime + x->AutoConnect;
2428 TreeServer* CheckDupe = FindServer(x->Name);
2431 // an autoconnected server is not connected. Check if its time to connect it
2432 WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
2433 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2434 Srv->AddSocket(newsocket);
2440 int HandleVersion(char** parameters, int pcnt, userrec* user)
2442 // we've already checked if pcnt > 0, so this is safe
2443 TreeServer* found = FindServerMask(parameters[0]);
2446 std::string Version = found->GetVersion();
2447 WriteServ(user->fd,"351 %s :%s",user->nick,Version.c_str());
2451 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
2456 int HandleConnect(char** parameters, int pcnt, userrec* user)
2458 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2460 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
2462 TreeServer* CheckDupe = FindServer(x->Name);
2465 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);
2466 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2467 Srv->AddSocket(newsocket);
2472 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());
2477 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
2481 virtual bool HandleStats(char ** parameters, int pcnt, userrec* user)
2483 if (*parameters[0] == 'c')
2485 for (unsigned int i = 0; i < LinkBlocks.size(); i++)
2487 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);
2488 WriteServ(user->fd,"244 %s H * * %s",user->nick,LinkBlocks[i].Name.c_str());
2490 WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
2491 WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
2497 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
2499 if (command == "CONNECT")
2501 return this->HandleConnect(parameters,pcnt,user);
2503 else if (command == "SQUIT")
2505 return this->HandleSquit(parameters,pcnt,user);
2507 else if (command == "STATS")
2509 return this->HandleStats(parameters,pcnt,user);
2511 else if (command == "MAP")
2513 this->HandleMap(parameters,pcnt,user);
2516 else if (command == "LUSERS")
2518 this->HandleLusers(parameters,pcnt,user);
2521 else if (command == "LINKS")
2523 this->HandleLinks(parameters,pcnt,user);
2526 else if (command == "WHOIS")
2531 return this->HandleRemoteWhois(parameters,pcnt,user);
2534 else if ((command == "VERSION") && (pcnt > 0))
2536 this->HandleVersion(parameters,pcnt,user);
2539 else if (Srv->IsValidModuleCommand(command, pcnt, user))
2541 // this bit of code cleverly routes all module commands
2542 // to all remote severs *automatically* so that modules
2543 // can just handle commands locally, without having
2544 // to have any special provision in place for remote
2545 // commands and linking protocols.
2546 std::deque<std::string> params;
2548 for (int j = 0; j < pcnt; j++)
2550 if (strchr(parameters[j],' '))
2552 params.push_back(":" + std::string(parameters[j]));
2556 params.push_back(std::string(parameters[j]));
2559 DoOneToMany(user->nick,command,params);
2564 virtual void OnGetServerDescription(std::string servername,std::string &description)
2566 TreeServer* s = FindServer(servername);
2569 description = s->GetDesc();
2573 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
2575 if (source->fd > -1)
2577 std::deque<std::string> params;
2578 params.push_back(dest->nick);
2579 params.push_back(channel->name);
2580 DoOneToMany(source->nick,"INVITE",params);
2584 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
2586 std::deque<std::string> params;
2587 params.push_back(chan->name);
2588 params.push_back(":"+topic);
2589 DoOneToMany(user->nick,"TOPIC",params);
2592 virtual void OnWallops(userrec* user, std::string text)
2596 std::deque<std::string> params;
2597 params.push_back(":"+text);
2598 DoOneToMany(user->nick,"WALLOPS",params);
2602 virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
2604 if (target_type == TYPE_USER)
2606 userrec* d = (userrec*)dest;
2607 if ((d->fd < 0) && (user->fd > -1))
2609 std::deque<std::string> params;
2611 params.push_back(d->nick);
2612 params.push_back(":"+text);
2613 DoOneToOne(user->nick,"NOTICE",params,d->server);
2620 chanrec *c = (chanrec*)dest;
2621 std::deque<TreeServer*> list;
2622 GetListOfServersForChannel(c,list);
2623 unsigned int ucount = list.size();
2624 for (unsigned int i = 0; i < ucount; i++)
2626 TreeSocket* Sock = list[i]->GetSocket();
2628 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+std::string(c->name)+" :"+text);
2634 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
2636 if (target_type == TYPE_USER)
2638 // route private messages which are targetted at clients only to the server
2639 // which needs to receive them
2640 userrec* d = (userrec*)dest;
2641 if ((d->fd < 0) && (user->fd > -1))
2643 std::deque<std::string> params;
2645 params.push_back(d->nick);
2646 params.push_back(":"+text);
2647 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
2654 chanrec *c = (chanrec*)dest;
2655 std::deque<TreeServer*> list;
2656 GetListOfServersForChannel(c,list);
2657 unsigned int ucount = list.size();
2658 for (unsigned int i = 0; i < ucount; i++)
2660 TreeSocket* Sock = list[i]->GetSocket();
2662 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+std::string(c->name)+" :"+text);
2668 virtual void OnBackgroundTimer(time_t curtime)
2670 AutoConnectServers(curtime);
2671 DoPingChecks(curtime);
2674 virtual void OnUserJoin(userrec* user, chanrec* channel)
2676 // Only do this for local users
2679 std::deque<std::string> params;
2681 params.push_back(channel->name);
2684 // if the channel has a key, force the join by emulating the key.
2685 params.push_back(channel->key);
2687 if (channel->GetUserCounter() > 1)
2689 // not the first in the channel
2690 DoOneToMany(user->nick,"JOIN",params);
2694 // first in the channel, set up their permissions
2695 // and the channel TS with FJOIN.
2697 snprintf(ts,24,"%lu",(unsigned long)channel->age);
2699 params.push_back(channel->name);
2700 params.push_back(ts);
2701 params.push_back("@"+std::string(user->nick));
2702 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
2707 virtual void OnChangeHost(userrec* user, std::string newhost)
2709 // only occurs for local clients
2710 if (user->registered != 7)
2712 std::deque<std::string> params;
2713 params.push_back(newhost);
2714 DoOneToMany(user->nick,"FHOST",params);
2717 virtual void OnChangeName(userrec* user, std::string gecos)
2719 // only occurs for local clients
2720 if (user->registered != 7)
2722 std::deque<std::string> params;
2723 params.push_back(gecos);
2724 DoOneToMany(user->nick,"FNAME",params);
2727 virtual void OnUserPart(userrec* user, chanrec* channel)
2731 std::deque<std::string> params;
2732 params.push_back(channel->name);
2733 DoOneToMany(user->nick,"PART",params);
2737 virtual void OnUserConnect(userrec* user)
2739 char agestr[MAXBUF];
2742 std::deque<std::string> params;
2743 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
2744 params.push_back(agestr);
2745 params.push_back(user->nick);
2746 params.push_back(user->host);
2747 params.push_back(user->dhost);
2748 params.push_back(user->ident);
2749 params.push_back("+"+std::string(user->modes));
2750 params.push_back(user->ip);
2751 params.push_back(":"+std::string(user->fullname));
2752 DoOneToMany(Srv->GetServerName(),"NICK",params);
2756 virtual void OnUserQuit(userrec* user, std::string reason)
2758 if ((user->fd > -1) && (user->registered == 7))
2760 std::deque<std::string> params;
2761 params.push_back(":"+reason);
2762 DoOneToMany(user->nick,"QUIT",params);
2766 virtual void OnUserPostNick(userrec* user, std::string oldnick)
2770 std::deque<std::string> params;
2771 params.push_back(user->nick);
2772 DoOneToMany(oldnick,"NICK",params);
2776 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
2778 if (source->fd > -1)
2780 std::deque<std::string> params;
2781 params.push_back(chan->name);
2782 params.push_back(user->nick);
2783 params.push_back(":"+reason);
2784 DoOneToMany(source->nick,"KICK",params);
2788 virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
2790 std::deque<std::string> params;
2791 params.push_back(dest->nick);
2792 params.push_back(":"+reason);
2793 DoOneToMany(source->nick,"KILL",params);
2796 virtual void OnRehash(std::string parameter)
2798 if (parameter != "")
2800 std::deque<std::string> params;
2801 params.push_back(parameter);
2802 DoOneToMany(Srv->GetServerName(),"REHASH",params);
2804 if (Srv->MatchText(Srv->GetServerName(),parameter))
2806 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
2807 Srv->RehashServer();
2810 ReadConfiguration(false);
2813 // note: the protocol does not allow direct umode +o except
2814 // via NICK with 8 params. sending OPERTYPE infers +o modechange
2816 virtual void OnOper(userrec* user, std::string opertype)
2820 std::deque<std::string> params;
2821 params.push_back(opertype);
2822 DoOneToMany(user->nick,"OPERTYPE",params);
2826 void OnLine(userrec* source, std::string host, bool adding, char linetype, long duration, std::string reason)
2828 if (source->fd > -1)
2831 snprintf(type,8,"%cLINE",linetype);
2832 std::string stype = type;
2835 char sduration[MAXBUF];
2836 snprintf(sduration,MAXBUF,"%ld",duration);
2837 std::deque<std::string> params;
2838 params.push_back(host);
2839 params.push_back(sduration);
2840 params.push_back(":"+reason);
2841 DoOneToMany(source->nick,stype,params);
2845 std::deque<std::string> params;
2846 params.push_back(host);
2847 DoOneToMany(source->nick,stype,params);
2852 virtual void OnAddGLine(long duration, userrec* source, std::string reason, std::string hostmask)
2854 OnLine(source,hostmask,true,'G',duration,reason);
2857 virtual void OnAddZLine(long duration, userrec* source, std::string reason, std::string ipmask)
2859 OnLine(source,ipmask,true,'Z',duration,reason);
2862 virtual void OnAddQLine(long duration, userrec* source, std::string reason, std::string nickmask)
2864 OnLine(source,nickmask,true,'Q',duration,reason);
2867 virtual void OnAddELine(long duration, userrec* source, std::string reason, std::string hostmask)
2869 OnLine(source,hostmask,true,'E',duration,reason);
2872 virtual void OnDelGLine(userrec* source, std::string hostmask)
2874 OnLine(source,hostmask,false,'G',0,"");
2877 virtual void OnDelZLine(userrec* source, std::string ipmask)
2879 OnLine(source,ipmask,false,'Z',0,"");
2882 virtual void OnDelQLine(userrec* source, std::string nickmask)
2884 OnLine(source,nickmask,false,'Q',0,"");
2887 virtual void OnDelELine(userrec* source, std::string hostmask)
2889 OnLine(source,hostmask,false,'E',0,"");
2892 virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
2894 if ((user->fd > -1) && (user->registered == 7))
2896 if (target_type == TYPE_USER)
2898 userrec* u = (userrec*)dest;
2899 std::deque<std::string> params;
2900 params.push_back(u->nick);
2901 params.push_back(text);
2902 DoOneToMany(user->nick,"MODE",params);
2906 chanrec* c = (chanrec*)dest;
2907 std::deque<std::string> params;
2908 params.push_back(c->name);
2909 params.push_back(text);
2910 DoOneToMany(user->nick,"MODE",params);
2915 virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
2917 TreeSocket* s = (TreeSocket*)opaque;
2920 if (target_type == TYPE_USER)
2922 userrec* u = (userrec*)target;
2923 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
2927 chanrec* c = (chanrec*)target;
2928 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
2933 virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, std::string extname, std::string extdata)
2935 TreeSocket* s = (TreeSocket*)opaque;
2938 if (target_type == TYPE_USER)
2940 userrec* u = (userrec*)target;
2941 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+u->nick+" "+extname+" :"+extdata);
2945 chanrec* c = (chanrec*)target;
2946 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+c->name+" "+extname+" :"+extdata);
2951 virtual ~ModuleSpanningTree()
2955 virtual Version GetVersion()
2957 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
2962 class ModuleSpanningTreeFactory : public ModuleFactory
2965 ModuleSpanningTreeFactory()
2969 ~ModuleSpanningTreeFactory()
2973 virtual Module * CreateModule(Server* Me)
2975 TreeProtocolModule = new ModuleSpanningTree(Me);
2976 return TreeProtocolModule;
2982 extern "C" void * init_module( void )
2984 return new ModuleSpanningTreeFactory;