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;
542 unsigned int keylength;
546 /* Because most of the I/O gubbins are encapsulated within
547 * InspSocket, we just call the superclass constructor for
548 * most of the action, and append a few of our own values
551 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
552 : InspSocket(host, port, listening, maxtime)
555 this->LinkState = LISTENER;
558 TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
559 : InspSocket(host, port, listening, maxtime)
562 this->LinkState = CONNECTING;
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)
570 : InspSocket(newfd, ip)
572 this->LinkState = WAIT_AUTH_1;
575 void InitAES(std::string key)
581 log(DEBUG,"Initialized AES key %s",key.c_str());
582 // key must be 16, 24, 32 etc bytes (multiple of 8)
583 keylength = key.length();
584 if (!(keylength == 16 || keylength == 24 || keylength == 32))
586 WriteOpers("\2ERROR\2: Key length for encryptionkey is not 16, 24 or 32 bytes in length!");
587 log(DEBUG,"Key length not 16, 24 or 32 characters!");
591 std::string SName = myhost;
592 if (InboundServerName != "")
594 SName = InboundServerName;
596 WriteOpers("\2AES\2: Initialized %d bit encryption to server %s",keylength*8,SName.c_str());
597 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\
598 \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);
602 /* When an outbound connection finishes connecting, we receive
603 * this event, and must send our SERVER string to the other
604 * side. If the other side is happy, as outlined in the server
605 * to server docs on the inspircd.org site, the other side
606 * will then send back its own server string.
608 virtual bool OnConnected()
610 if (this->LinkState == CONNECTING)
612 Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
613 /* we do not need to change state here. */
614 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
616 if (x->Name == this->myhost)
618 /* found who we're supposed to be connecting to, send the neccessary gubbins. */
619 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
624 /* There is a (remote) chance that between the /CONNECT and the connection
625 * being accepted, some muppet has removed the <link> block and rehashed.
626 * If that happens the connection hangs here until it's closed. Unlikely
627 * and rather harmless.
632 virtual void OnError(InspSocketError e)
634 /* We don't handle this method, because all our
635 * dirty work is done in OnClose() (see below)
636 * which is still called on error conditions too.
640 virtual int OnDisconnect()
642 /* For the same reason as above, we don't
643 * handle OnDisconnect()
648 /* Recursively send the server tree with distances as hops.
649 * This is used during network burst to inform the other server
650 * (and any of ITS servers too) of what servers we know about.
651 * If at any point any of these servers already exist on the other
652 * end, our connection may be terminated. The hopcounts given
653 * by this function are relative, this doesn't matter so long as
654 * they are all >1, as all the remote servers re-calculate them
655 * to be relative too, with themselves as hop 0.
657 void SendServers(TreeServer* Current, TreeServer* s, int hops)
660 for (unsigned int q = 0; q < Current->ChildCount(); q++)
662 TreeServer* recursive_server = Current->GetChild(q);
663 if (recursive_server != s)
665 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
666 this->WriteLine(command);
667 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
668 /* down to next level */
669 this->SendServers(recursive_server, s, hops+1);
674 /* This function forces this server to quit, removing this server
675 * and any users on it (and servers and users below that, etc etc).
676 * It's very slow and pretty clunky, but luckily unless your network
677 * is having a REAL bad hair day, this function shouldnt be called
678 * too many times a month ;-)
680 void SquitServer(TreeServer* Current, CullList* Goners)
682 /* recursively squit the servers attached to 'Current'.
683 * We're going backwards so we don't remove users
684 * while we still need them ;)
686 for (unsigned int q = 0; q < Current->ChildCount(); q++)
688 TreeServer* recursive_server = Current->GetChild(q);
689 this->SquitServer(recursive_server,Goners);
691 /* Now we've whacked the kids, whack self */
693 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
695 if (!strcasecmp(u->second->server,Current->GetName().c_str()))
697 std::string qreason = Current->GetName()+" "+std::string(Srv->GetServerName());
698 Goners->AddItem(u->second,qreason);
704 /* This is a wrapper function for SquitServer above, which
705 * does some validation first and passes on the SQUIT to all
706 * other remaining servers.
708 void Squit(TreeServer* Current,std::string reason)
712 std::deque<std::string> params;
713 params.push_back(Current->GetName());
714 params.push_back(":"+reason);
715 DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
716 if (Current->GetParent() == TreeRoot)
718 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
722 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
724 num_lost_servers = 0;
726 CullList* Goners = new CullList();
727 SquitServer(Current, Goners);
730 Current->GetParent()->DelChild(Current);
733 WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
737 log(DEFAULT,"Squit from unknown server");
742 bool ForceMode(std::string source, std::deque<std::string> params)
744 userrec* who = new userrec;
745 who->fd = FD_MAGIC_NUMBER;
746 if (params.size() < 2)
749 for (unsigned int q = 0; q < params.size(); q++)
751 modelist[q] = (char*)params[q].c_str();
753 Srv->SendMode(modelist,params.size(),who);
754 DoOneToAllButSender(source,"FMODE",params,source);
760 bool ForceTopic(std::string source, std::deque<std::string> params)
762 if (params.size() != 4)
764 std::string channel = params[0];
765 time_t ts = atoi(params[1].c_str());
766 std::string setby = params[2];
767 std::string topic = params[3];
769 chanrec* c = Srv->FindChannel(channel);
772 if ((ts >= c->topicset) || (!*c->topic))
774 std::string oldtopic = c->topic;
775 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
776 strlcpy(c->setby,setby.c_str(),NICKMAX);
778 /* if the topic text is the same as the current topic,
779 * dont bother to send the TOPIC command out, just silently
780 * update the set time and set nick.
782 if (oldtopic != topic)
783 WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
788 /* all done, send it on its way */
789 params[3] = ":" + params[3];
790 DoOneToAllButSender(source,"FTOPIC",params,source);
795 /* FJOIN, similar to unreal SJOIN */
796 bool ForceJoin(std::string source, std::deque<std::string> params)
798 if (params.size() < 3)
802 char modestring[MAXBUF];
803 char* mode_users[127];
804 mode_users[0] = first;
805 mode_users[1] = modestring;
806 strcpy(mode_users[1],"+");
807 unsigned int modectr = 2;
810 std::string channel = params[0];
811 time_t TS = atoi(params[1].c_str());
814 chanrec* chan = Srv->FindChannel(channel);
819 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
821 /* default is a high value, which if we dont have this
822 * channel will let the other side apply their modes.
824 time_t ourTS = time(NULL)+600;
825 chanrec* us = Srv->FindChannel(channel);
831 log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
833 /* do this first, so our mode reversals are correctly received by other servers
834 * if there is a TS collision.
836 DoOneToAllButSender(source,"FJOIN",params,source);
838 for (unsigned int usernum = 2; usernum < params.size(); usernum++)
840 /* process one channel at a time, applying modes. */
841 char* usr = (char*)params[usernum].c_str();
842 char permissions = *usr;
847 mode_users[modectr++] = usr;
848 strlcat(modestring,"o",MAXBUF);
852 mode_users[modectr++] = usr;
853 strlcat(modestring,"h",MAXBUF);
857 mode_users[modectr++] = usr;
858 strlcat(modestring,"v",MAXBUF);
861 who = Srv->FindNick(usr);
864 Srv->JoinUserToChannel(who,channel,key);
865 if (modectr >= (MAXMODES-1))
867 /* theres a mode for this user. push them onto the mode queue, and flush it
868 * if there are more than MAXMODES to go.
870 if ((ourTS >= TS) || (Srv->IsUlined(who->server)))
872 /* We also always let u-lined clients win, no matter what the TS value */
873 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
874 Srv->SendMode(mode_users,modectr,who);
878 log(DEBUG,"Their channel newer than ours, bouncing their modes");
880 std::deque<std::string> params;
881 /* modes are now being UNSET... */
882 *mode_users[1] = '-';
883 for (unsigned int x = 0; x < modectr; x++)
885 params.push_back(mode_users[x]);
887 // tell everyone to bounce the modes. bad modes, bad!
888 DoOneToMany(Srv->GetServerName(),"FMODE",params);
890 strcpy(mode_users[1],"+");
895 /* there werent enough modes built up to flush it during FJOIN,
896 * or, there are a number left over. flush them out.
898 if ((modectr > 2) && (who))
902 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
903 Srv->SendMode(mode_users,modectr,who);
907 log(DEBUG,"Their channel newer than ours, bouncing their modes");
908 std::deque<std::string> params;
909 *mode_users[1] = '-';
910 for (unsigned int x = 0; x < modectr; x++)
912 params.push_back(mode_users[x]);
914 DoOneToMany(Srv->GetServerName(),"FMODE",params);
921 bool IntroduceClient(std::string source, std::deque<std::string> params)
923 if (params.size() < 8)
925 // NICK age nick host dhost ident +modes ip :gecos
927 std::string nick = params[1];
928 std::string host = params[2];
929 std::string dhost = params[3];
930 std::string ident = params[4];
931 time_t age = atoi(params[0].c_str());
932 std::string modes = params[5];
933 while (*(modes.c_str()) == '+')
935 char* m = (char*)modes.c_str();
939 std::string ip = params[6];
940 std::string gecos = params[7];
941 char* tempnick = (char*)nick.c_str();
942 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
944 user_hash::iterator iter;
945 iter = clientlist.find(tempnick);
946 if (iter != clientlist.end())
949 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);
950 this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
954 clientlist[tempnick] = new userrec();
955 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
956 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
957 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
958 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
959 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
960 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
961 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
962 clientlist[tempnick]->registered = 7;
963 clientlist[tempnick]->signon = age;
964 strlcpy(clientlist[tempnick]->modes, modes.c_str(),53);
965 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
970 for (int i = 0; i < MAXCHANS; i++)
971 clientlist[tempnick]->chans.push_back(a);
975 WriteOpers("*** Client connecting at %s: %s!%s@%s [%s]",clientlist[tempnick]->server,clientlist[tempnick]->nick,clientlist[tempnick]->ident,clientlist[tempnick]->host,clientlist[tempnick]->ip);
977 params[7] = ":" + params[7];
978 DoOneToAllButSender(source,"NICK",params,source);
982 /* Send one or more FJOINs for a channel of users.
983 * If the length of a single line is more than 480-NICKMAX
984 * in length, it is split over multiple lines.
986 void SendFJoins(TreeServer* Current, chanrec* c)
988 log(DEBUG,"Sending FJOINs to other server for %s",c->name);
990 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
991 std::vector<char*> *ulist = c->GetUsers();
992 for (unsigned int i = 0; i < ulist->size(); i++)
994 char* o = (*ulist)[i];
995 userrec* otheruser = (userrec*)o;
996 strlcat(list," ",MAXBUF);
997 strlcat(list,cmode(otheruser,c),MAXBUF);
998 strlcat(list,otheruser->nick,MAXBUF);
999 if (strlen(list)>(480-NICKMAX))
1001 log(DEBUG,"FJOIN line wrapped");
1002 this->WriteLine(list);
1003 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1006 if (list[strlen(list)-1] != ':')
1008 log(DEBUG,"Final FJOIN line");
1009 this->WriteLine(list);
1013 /* Send G, Q, Z and E lines */
1014 void SendXLines(TreeServer* Current)
1017 /* Yes, these arent too nice looking, but they get the job done */
1018 for (std::vector<ZLine>::iterator i = zlines.begin(); i != zlines.end(); i++)
1020 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);
1021 this->WriteLine(data);
1023 for (std::vector<QLine>::iterator i = qlines.begin(); i != qlines.end(); i++)
1025 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);
1026 this->WriteLine(data);
1028 for (std::vector<GLine>::iterator i = glines.begin(); i != glines.end(); i++)
1030 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);
1031 this->WriteLine(data);
1033 for (std::vector<ELine>::iterator i = elines.begin(); i != elines.end(); i++)
1035 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);
1036 this->WriteLine(data);
1038 for (std::vector<ZLine>::iterator i = pzlines.begin(); i != pzlines.end(); i++)
1040 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);
1041 this->WriteLine(data);
1043 for (std::vector<QLine>::iterator i = pqlines.begin(); i != pqlines.end(); i++)
1045 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);
1046 this->WriteLine(data);
1048 for (std::vector<GLine>::iterator i = pglines.begin(); i != pglines.end(); i++)
1050 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);
1051 this->WriteLine(data);
1053 for (std::vector<ELine>::iterator i = pelines.begin(); i != pelines.end(); i++)
1055 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);
1056 this->WriteLine(data);
1060 /* Send channel modes and topics */
1061 void SendChannelModes(TreeServer* Current)
1064 std::deque<std::string> list;
1065 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
1067 SendFJoins(Current, c->second);
1068 snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
1069 this->WriteLine(data);
1070 if (*c->second->topic)
1072 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);
1073 this->WriteLine(data);
1075 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
1077 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
1078 this->WriteLine(data);
1080 FOREACH_MOD OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this);
1082 c->second->GetExtList(list);
1083 for (unsigned int j = 0; j < list.size(); j++)
1085 FOREACH_MOD OnSyncChannelMetaData(c->second,(Module*)TreeProtocolModule,(void*)this,list[j]);
1090 /* send all users and their oper state/modes */
1091 void SendUsers(TreeServer* Current)
1094 std::deque<std::string> list;
1095 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
1097 if (u->second->registered == 7)
1099 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);
1100 this->WriteLine(data);
1101 if (strchr(u->second->modes,'o'))
1103 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
1105 FOREACH_MOD OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this);
1107 u->second->GetExtList(list);
1108 for (unsigned int j = 0; j < list.size(); j++)
1110 FOREACH_MOD OnSyncUserMetaData(u->second,(Module*)TreeProtocolModule,(void*)this,list[j]);
1116 /* This function is called when we want to send a netburst to a local
1117 * server. There is a set order we must do this, because for example
1118 * users require their servers to exist, and channels require their
1119 * users to exist. You get the idea.
1121 void DoBurst(TreeServer* s)
1123 Srv->SendOpers("*** Bursting to \2"+s->GetName()+"\2.");
1124 this->WriteLine("BURST");
1125 /* send our version string */
1126 this->WriteLine(":"+Srv->GetServerName()+" VERSION :"+Srv->GetVersion());
1127 /* Send server tree */
1128 this->SendServers(TreeRoot,s,1);
1129 /* Send users and their oper status */
1131 /* Send everything else (channel modes, xlines etc) */
1132 this->SendChannelModes(s);
1133 this->SendXLines(s);
1134 this->WriteLine("ENDBURST");
1135 Srv->SendOpers("*** Finished bursting to \2"+s->GetName()+"\2.");
1138 /* This function is called when we receive data from a remote
1139 * server. We buffer the data in a std::string (it doesnt stay
1140 * there for long), reading using InspSocket::Read() which can
1141 * read up to 16 kilobytes in one operation.
1143 * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
1144 * THE SOCKET OBJECT FOR US.
1146 virtual bool OnDataReady()
1148 char* data = this->Read();
1151 this->in_buffer += data;
1152 /* While there is at least one new line in the buffer,
1153 * do something useful (we hope!) with it.
1155 while (in_buffer.find("\n") != std::string::npos)
1157 char* line = (char*)in_buffer.c_str();
1158 std::string ret = "";
1159 while ((*line != '\n') && (strlen(line)))
1164 if ((*line == '\n') || (*line == '\r'))
1167 /* Process this one, abort if it
1168 * didnt return true.
1174 log(DEBUG,"Original string '%s'",ret.c_str());
1175 int nbytes = from64tobits(out, ret.c_str(), 1024);
1176 log(DEBUG,"m_spanningtree: decrypt %d bytes",nbytes);
1177 ctx->Decrypt(out, result, nbytes, 0);
1178 for (int t = 0; t < nbytes; t++)
1179 if (result[t] == '\7') result[t] = 0;
1182 if (!this->ProcessLine(ret))
1188 return (data != NULL);
1191 int WriteLine(std::string line)
1193 log(DEBUG,"OUT: %s",line.c_str());
1196 log(DEBUG,"AES context");
1198 char result64[1024];
1199 if (this->keylength)
1201 while (line.length() % this->keylength != 0)
1203 // pad it to be a multiple of the key length
1207 ctx->Encrypt(line.c_str(), result, line.length(),0);
1208 to64frombits((unsigned char*)result64,
1209 (unsigned char*)result,
1212 log(DEBUG,"Encrypted: %s",line.c_str());
1213 //int from64tobits(char *out, const char *in, int maxlen);
1215 return this->Write(line + "\r\n");
1218 /* Handle ERROR command */
1219 bool Error(std::deque<std::string> params)
1221 if (params.size() < 1)
1223 std::string Errmsg = params[0];
1224 std::string SName = myhost;
1225 if (InboundServerName != "")
1227 SName = InboundServerName;
1229 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
1230 /* we will return false to cause the socket to close.
1235 /* Because the core won't let users or even SERVERS set +o,
1236 * we use the OPERTYPE command to do this.
1238 bool OperType(std::string prefix, std::deque<std::string> ¶ms)
1240 if (params.size() != 1)
1242 std::string opertype = params[0];
1243 userrec* u = Srv->FindNick(prefix);
1246 strlcpy(u->oper,opertype.c_str(),NICKMAX);
1247 if (!strchr(u->modes,'o'))
1249 strcat(u->modes,"o");
1251 DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
1256 /* Because Andy insists that services-compatible servers must
1257 * implement SVSNICK and SVSJOIN, that's exactly what we do :p
1259 bool ForceNick(std::string prefix, std::deque<std::string> ¶ms)
1261 if (params.size() < 3)
1263 userrec* u = Srv->FindNick(params[0]);
1266 Srv->ChangeUserNick(u,params[1]);
1267 u->age = atoi(params[2].c_str());
1268 DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
1273 bool ServiceJoin(std::string prefix, std::deque<std::string> ¶ms)
1275 if (params.size() < 2)
1277 userrec* u = Srv->FindNick(params[0]);
1280 Srv->JoinUserToChannel(u,params[1],"");
1281 DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
1286 bool RemoteRehash(std::string prefix, std::deque<std::string> ¶ms)
1288 if (params.size() < 1)
1290 std::string servermask = params[0];
1291 if (Srv->MatchText(Srv->GetServerName(),servermask))
1293 Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
1294 Srv->RehashServer();
1295 ReadConfiguration(false);
1297 DoOneToAllButSender(prefix,"REHASH",params,prefix);
1301 bool RemoteKill(std::string prefix, std::deque<std::string> ¶ms)
1303 if (params.size() != 2)
1305 std::string nick = params[0];
1306 userrec* u = Srv->FindNick(prefix);
1307 userrec* who = Srv->FindNick(nick);
1310 /* Prepend kill source, if we don't have one */
1311 std::string sourceserv = prefix;
1314 sourceserv = u->server;
1316 if (*(params[1].c_str()) != '[')
1318 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
1320 std::string reason = params[1];
1321 params[1] = ":" + params[1];
1322 DoOneToAllButSender(prefix,"KILL",params,sourceserv);
1323 Srv->QuitUser(who,reason);
1328 bool LocalPong(std::string prefix, std::deque<std::string> ¶ms)
1330 if (params.size() < 1)
1332 TreeServer* ServerSource = FindServer(prefix);
1335 ServerSource->SetPingFlag();
1340 bool MetaData(std::string prefix, std::deque<std::string> ¶ms)
1342 if (params.size() < 3)
1344 TreeServer* ServerSource = FindServer(prefix);
1347 if (*(params[0].c_str()) == '#')
1349 chanrec* c = Srv->FindChannel(params[0]);
1352 FOREACH_MOD OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]);
1357 userrec* u = Srv->FindNick(params[0]);
1360 FOREACH_MOD OnDecodeMetaData(TYPE_USER,u,params[1],params[2]);
1364 params[2] = ":" + params[2];
1365 DoOneToAllButSender(prefix,"METADATA",params,prefix);
1369 bool ServerVersion(std::string prefix, std::deque<std::string> ¶ms)
1371 if (params.size() < 1)
1373 TreeServer* ServerSource = FindServer(prefix);
1376 ServerSource->SetVersion(params[0]);
1378 params[0] = ":" + params[0];
1379 DoOneToAllButSender(prefix,"VERSION",params,prefix);
1383 bool ChangeHost(std::string prefix, std::deque<std::string> ¶ms)
1385 if (params.size() < 1)
1387 userrec* u = Srv->FindNick(prefix);
1390 Srv->ChangeHost(u,params[0]);
1391 DoOneToAllButSender(prefix,"FHOST",params,u->server);
1396 bool AddLine(std::string prefix, std::deque<std::string> ¶ms)
1398 if (params.size() < 6)
1400 std::string linetype = params[0]; /* Z, Q, E, G, K */
1401 std::string mask = params[1]; /* Line type dependent */
1402 std::string source = params[2]; /* may not be online or may be a server */
1403 std::string settime = params[3]; /* EPOCH time set */
1404 std::string duration = params[4]; /* Duration secs */
1405 std::string reason = params[5];
1407 switch (*(linetype.c_str()))
1410 add_zline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1411 zline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1414 add_qline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1415 qline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1418 add_eline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1419 eline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1422 add_gline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1423 gline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1426 add_kline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1429 /* Just in case... */
1430 Srv->SendOpers("*** \2WARNING\2: Invalid xline type '"+linetype+"' sent by server "+prefix+", ignored!");
1433 /* Send it on its way */
1434 params[5] = ":" + params[5];
1435 DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
1439 bool ChangeName(std::string prefix, std::deque<std::string> ¶ms)
1441 if (params.size() < 1)
1443 userrec* u = Srv->FindNick(prefix);
1446 Srv->ChangeGECOS(u,params[0]);
1447 params[0] = ":" + params[0];
1448 DoOneToAllButSender(prefix,"FNAME",params,u->server);
1453 bool Whois(std::string prefix, std::deque<std::string> ¶ms)
1455 if (params.size() < 1)
1457 log(DEBUG,"In IDLE command");
1458 userrec* u = Srv->FindNick(prefix);
1461 log(DEBUG,"USER EXISTS: %s",u->nick);
1462 // an incoming request
1463 if (params.size() == 1)
1465 userrec* x = Srv->FindNick(params[0]);
1468 userrec* x = Srv->FindNick(params[0]);
1469 log(DEBUG,"Got IDLE");
1470 char signon[MAXBUF];
1472 log(DEBUG,"Sending back IDLE 3");
1473 snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
1474 snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-time(NULL)));
1475 std::deque<std::string> par;
1476 par.push_back(prefix);
1477 par.push_back(signon);
1478 par.push_back(idle);
1479 // ours, we're done, pass it BACK
1480 DoOneToOne(params[0],"IDLE",par,u->server);
1484 // not ours pass it on
1485 DoOneToOne(prefix,"IDLE",params,x->server);
1488 else if (params.size() == 3)
1490 std::string who_did_the_whois = params[0];
1491 userrec* who_to_send_to = Srv->FindNick(who_did_the_whois);
1492 if (who_to_send_to->fd > -1)
1494 log(DEBUG,"Got final IDLE");
1495 // an incoming reply to a whois we sent out
1496 std::string nick_whoised = prefix;
1497 unsigned long signon = atoi(params[1].c_str());
1498 unsigned long idle = atoi(params[2].c_str());
1499 if ((who_to_send_to) && (who_to_send_to->fd > -1))
1500 do_whois(who_to_send_to,u,signon,idle,(char*)nick_whoised.c_str());
1504 // not ours, pass it on
1505 DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
1512 bool LocalPing(std::string prefix, std::deque<std::string> ¶ms)
1514 if (params.size() < 1)
1516 std::string stufftobounce = params[0];
1517 this->WriteLine(":"+Srv->GetServerName()+" PONG "+stufftobounce);
1521 bool RemoteServer(std::string prefix, std::deque<std::string> ¶ms)
1523 if (params.size() < 4)
1525 std::string servername = params[0];
1526 std::string password = params[1];
1527 // hopcount is not used for a remote server, we calculate this ourselves
1528 std::string description = params[3];
1529 TreeServer* ParentOfThis = FindServer(prefix);
1532 this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
1535 TreeServer* CheckDupe = FindServer(servername);
1538 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1541 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
1542 ParentOfThis->AddChild(Node);
1543 params[3] = ":" + params[3];
1544 DoOneToAllButSender(prefix,"SERVER",params,prefix);
1545 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
1549 bool Outbound_Reply_Server(std::deque<std::string> ¶ms)
1551 if (params.size() < 4)
1553 std::string servername = params[0];
1554 std::string password = params[1];
1555 int hops = atoi(params[2].c_str());
1558 this->WriteLine("ERROR :Server too far away for authentication");
1561 std::string description = params[3];
1562 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1564 if ((x->Name == servername) && (x->RecvPass == password))
1566 TreeServer* CheckDupe = FindServer(servername);
1569 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1572 // Begin the sync here. this kickstarts the
1573 // other side, waiting in WAIT_AUTH_2 state,
1574 // into starting their burst, as it shows
1575 // that we're happy.
1576 this->LinkState = CONNECTED;
1577 // we should add the details of this server now
1578 // to the servers tree, as a child of the root
1580 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
1581 TreeRoot->AddChild(Node);
1582 params[3] = ":" + params[3];
1583 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
1584 this->bursting = true;
1585 this->DoBurst(Node);
1589 this->WriteLine("ERROR :Invalid credentials");
1593 bool Inbound_Server(std::deque<std::string> ¶ms)
1595 if (params.size() < 4)
1597 std::string servername = params[0];
1598 std::string password = params[1];
1599 int hops = atoi(params[2].c_str());
1602 this->WriteLine("ERROR :Server too far away for authentication");
1605 std::string description = params[3];
1606 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1608 if ((x->Name == servername) && (x->RecvPass == password))
1610 TreeServer* CheckDupe = FindServer(servername);
1613 this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1616 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
1617 this->InboundServerName = servername;
1618 this->InboundDescription = description;
1619 // this is good. Send our details: Our server name and description and hopcount of 0,
1620 // along with the sendpass from this block.
1621 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
1622 // move to the next state, we are now waiting for THEM.
1623 this->LinkState = WAIT_AUTH_2;
1627 this->WriteLine("ERROR :Invalid credentials");
1631 void Split(std::string line, bool stripcolon, std::deque<std::string> &n)
1633 if (!strchr(line.c_str(),' '))
1638 std::stringstream s(line);
1639 std::string param = "";
1658 if ((param == ":") && (item > 0))
1681 bool ProcessLine(std::string line)
1683 char* l = (char*)line.c_str();
1684 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
1685 l[strlen(l)-1] = '\0';
1689 Srv->Log(DEBUG,"IN: "+line);
1690 std::deque<std::string> params;
1691 this->Split(line,true,params);
1692 std::string command = "";
1693 std::string prefix = "";
1694 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
1697 command = params[1];
1698 char* pref = (char*)prefix.c_str();
1706 command = params[0];
1710 switch (this->LinkState)
1715 // Waiting for SERVER command from remote server. Server initiating
1716 // the connection sends the first SERVER command, listening server
1717 // replies with theirs if its happy, then if the initiator is happy,
1718 // it starts to send its net sync, which starts the merge, otherwise
1719 // it sends an ERROR.
1720 if (command == "SERVER")
1722 return this->Inbound_Server(params);
1724 else if (command == "ERROR")
1726 return this->Error(params);
1730 // Waiting for start of other side's netmerge to say they liked our
1732 if (command == "SERVER")
1734 // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1738 else if (command == "BURST")
1740 this->LinkState = CONNECTED;
1741 Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
1742 TreeRoot->AddChild(Node);
1744 params.push_back(InboundServerName);
1745 params.push_back("*");
1746 params.push_back("1");
1747 params.push_back(":"+InboundDescription);
1748 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
1749 this->bursting = true;
1750 this->DoBurst(Node);
1752 else if (command == "ERROR")
1754 return this->Error(params);
1759 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
1763 if (command == "SERVER")
1765 // another server we connected to, which was in WAIT_AUTH_1 state,
1766 // has just sent us their credentials. If we get this far, theyre
1767 // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1768 // if we're happy with this, we should send our netburst which
1769 // kickstarts the merge.
1770 return this->Outbound_Reply_Server(params);
1772 else if (command == "ERROR")
1774 return this->Error(params);
1778 // This is the 'authenticated' state, when all passwords
1779 // have been exchanged and anything past this point is taken
1784 std::string direction = prefix;
1785 userrec* t = Srv->FindNick(prefix);
1788 direction = t->server;
1790 TreeServer* route_back_again = BestRouteTo(direction);
1791 if ((!route_back_again) || (route_back_again->GetSocket() != this))
1793 if (route_back_again)
1795 WriteOpers("Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
1799 WriteOpers("Protocol violation: Invalid source '%s' in command '%s' from connection '%s'",direction.c_str(),line.c_str(),this->GetName().c_str());
1806 if (command == "SVSMODE")
1808 /* Services expects us to implement
1809 * SVSMODE. In inspircd its the same as
1814 std::string target = "";
1815 /* Yes, know, this is a mess. Its reasonably fast though as we're
1816 * working with std::string here.
1818 if ((command == "NICK") && (params.size() > 1))
1820 return this->IntroduceClient(prefix,params);
1822 else if (command == "FJOIN")
1824 return this->ForceJoin(prefix,params);
1826 else if (command == "SERVER")
1828 return this->RemoteServer(prefix,params);
1830 else if (command == "ERROR")
1832 return this->Error(params);
1834 else if (command == "OPERTYPE")
1836 return this->OperType(prefix,params);
1838 else if (command == "FMODE")
1840 return this->ForceMode(prefix,params);
1842 else if (command == "KILL")
1844 return this->RemoteKill(prefix,params);
1846 else if (command == "FTOPIC")
1848 return this->ForceTopic(prefix,params);
1850 else if (command == "REHASH")
1852 return this->RemoteRehash(prefix,params);
1854 else if (command == "METADATA")
1856 return this->MetaData(prefix,params);
1858 else if (command == "PING")
1860 return this->LocalPing(prefix,params);
1862 else if (command == "PONG")
1864 return this->LocalPong(prefix,params);
1866 else if (command == "VERSION")
1868 return this->ServerVersion(prefix,params);
1870 else if (command == "FHOST")
1872 return this->ChangeHost(prefix,params);
1874 else if (command == "FNAME")
1876 return this->ChangeName(prefix,params);
1878 else if (command == "ADDLINE")
1880 return this->AddLine(prefix,params);
1882 else if (command == "SVSNICK")
1886 prefix = this->GetName();
1888 return this->ForceNick(prefix,params);
1890 else if (command == "IDLE")
1892 return this->Whois(prefix,params);
1894 else if (command == "SVSJOIN")
1898 prefix = this->GetName();
1900 return this->ServiceJoin(prefix,params);
1902 else if (command == "SQUIT")
1904 if (params.size() == 2)
1906 this->Squit(FindServer(params[0]),params[1]);
1910 else if (command == "ENDBURST")
1912 this->bursting = false;
1913 std::string sserv = this->myhost;
1914 if (this->InboundServerName != "")
1915 sserv = this->InboundServerName;
1916 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1918 if ((x->EncryptionKey != "") && (x->Name == sserv))
1920 this->InitAES(x->EncryptionKey);
1927 // not a special inter-server command.
1928 // Emulate the actual user doing the command,
1929 // this saves us having a huge ugly parser.
1930 userrec* who = Srv->FindNick(prefix);
1931 std::string sourceserv = this->myhost;
1932 if (this->InboundServerName != "")
1934 sourceserv = this->InboundServerName;
1939 target = who->server;
1940 char* strparams[127];
1941 for (unsigned int q = 0; q < params.size(); q++)
1943 strparams[q] = (char*)params[q].c_str();
1945 Srv->CallCommandHandler(command, strparams, params.size(), who);
1949 // its not a user. Its either a server, or somethings screwed up.
1950 if (IsServer(prefix))
1952 target = Srv->GetServerName();
1956 log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
1960 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1969 virtual std::string GetName()
1971 std::string sourceserv = this->myhost;
1972 if (this->InboundServerName != "")
1974 sourceserv = this->InboundServerName;
1979 virtual void OnTimeout()
1981 if (this->LinkState == CONNECTING)
1983 Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
1987 virtual void OnClose()
1989 // Connection closed.
1990 // If the connection is fully up (state CONNECTED)
1991 // then propogate a netsplit to all peers.
1992 std::string quitserver = this->myhost;
1993 if (this->InboundServerName != "")
1995 quitserver = this->InboundServerName;
1997 TreeServer* s = FindServer(quitserver);
2000 Squit(s,"Remote host closed the connection");
2004 virtual int OnIncomingConnection(int newsock, char* ip)
2006 TreeSocket* s = new TreeSocket(newsock, ip);
2012 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
2014 for (unsigned int c = 0; c < list.size(); c++)
2016 if (list[c] == server)
2021 list.push_back(server);
2024 // returns a list of DIRECT servernames for a specific channel
2025 void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
2027 std::vector<char*> *ulist = c->GetUsers();
2028 unsigned int ucount = ulist->size();
2029 for (unsigned int i = 0; i < ucount; i++)
2031 char* o = (*ulist)[i];
2032 userrec* otheruser = (userrec*)o;
2033 if (otheruser->fd < 0)
2035 TreeServer* best = BestRouteTo(otheruser->server);
2037 AddThisServer(best,list);
2043 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, std::string command, std::deque<std::string> ¶ms)
2045 TreeServer* omitroute = BestRouteTo(omit);
2046 if ((command == "NOTICE") || (command == "PRIVMSG"))
2048 if ((params.size() >= 2) && (*(params[0].c_str()) != '$'))
2050 if (*(params[0].c_str()) != '#')
2052 // special routing for private messages/notices
2053 userrec* d = Srv->FindNick(params[0]);
2056 std::deque<std::string> par;
2057 par.push_back(params[0]);
2058 par.push_back(":"+params[1]);
2059 DoOneToOne(prefix,command,par,d->server);
2065 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
2066 chanrec* c = Srv->FindChannel(params[0]);
2069 std::deque<TreeServer*> list;
2070 GetListOfServersForChannel(c,list);
2071 log(DEBUG,"Got a list of %d servers",list.size());
2072 unsigned int lsize = list.size();
2073 for (unsigned int i = 0; i < lsize; i++)
2075 TreeSocket* Sock = list[i]->GetSocket();
2076 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
2078 log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
2079 Sock->WriteLine(data);
2087 unsigned int items = TreeRoot->ChildCount();
2088 for (unsigned int x = 0; x < items; x++)
2090 TreeServer* Route = TreeRoot->GetChild(x);
2091 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
2093 TreeSocket* Sock = Route->GetSocket();
2094 Sock->WriteLine(data);
2100 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string omit)
2102 TreeServer* omitroute = BestRouteTo(omit);
2103 std::string FullLine = ":" + prefix + " " + command;
2104 unsigned int words = params.size();
2105 for (unsigned int x = 0; x < words; x++)
2107 FullLine = FullLine + " " + params[x];
2109 unsigned int items = TreeRoot->ChildCount();
2110 for (unsigned int x = 0; x < items; x++)
2112 TreeServer* Route = TreeRoot->GetChild(x);
2113 // Send the line IF:
2114 // The route has a socket (its a direct connection)
2115 // The route isnt the one to be omitted
2116 // The route isnt the path to the one to be omitted
2117 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
2119 TreeSocket* Sock = Route->GetSocket();
2120 Sock->WriteLine(FullLine);
2126 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> ¶ms)
2128 std::string FullLine = ":" + prefix + " " + command;
2129 unsigned int words = params.size();
2130 for (unsigned int x = 0; x < words; x++)
2132 FullLine = FullLine + " " + params[x];
2134 unsigned int items = TreeRoot->ChildCount();
2135 for (unsigned int x = 0; x < items; x++)
2137 TreeServer* Route = TreeRoot->GetChild(x);
2138 if (Route->GetSocket())
2140 TreeSocket* Sock = Route->GetSocket();
2141 Sock->WriteLine(FullLine);
2147 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> ¶ms, std::string target)
2149 TreeServer* Route = BestRouteTo(target);
2152 std::string FullLine = ":" + prefix + " " + command;
2153 unsigned int words = params.size();
2154 for (unsigned int x = 0; x < words; x++)
2156 FullLine = FullLine + " " + params[x];
2158 if (Route->GetSocket())
2160 TreeSocket* Sock = Route->GetSocket();
2161 Sock->WriteLine(FullLine);
2171 std::vector<TreeSocket*> Bindings;
2173 void ReadConfiguration(bool rebind)
2175 Conf = new ConfigReader;
2178 for (int j =0; j < Conf->Enumerate("bind"); j++)
2180 std::string Type = Conf->ReadValue("bind","type",j);
2181 std::string IP = Conf->ReadValue("bind","address",j);
2182 long Port = Conf->ReadInteger("bind","port",j,true);
2183 if (Type == "servers")
2189 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
2190 if (listener->GetState() == I_LISTENING)
2192 Srv->AddSocket(listener);
2193 Bindings.push_back(listener);
2197 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
2205 for (int j =0; j < Conf->Enumerate("link"); j++)
2208 L.Name = Conf->ReadValue("link","name",j);
2209 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
2210 L.Port = Conf->ReadInteger("link","port",j,true);
2211 L.SendPass = Conf->ReadValue("link","sendpass",j);
2212 L.RecvPass = Conf->ReadValue("link","recvpass",j);
2213 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
2214 L.EncryptionKey = Conf->ReadValue("link","encryptionkey",j);
2215 L.NextConnectTime = time(NULL) + L.AutoConnect;
2216 /* Bugfix by brain, do not allow people to enter bad configurations */
2217 if ((L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
2219 LinkBlocks.push_back(L);
2220 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
2224 log(DEFAULT,"m_spanningtree: Invalid configuration for server '%s', ignored!",L.Name.c_str());
2231 class ModuleSpanningTree : public Module
2233 std::vector<TreeSocket*> Bindings;
2239 ModuleSpanningTree(Server* Me)
2240 : Module::Module(Me)
2245 // Create the root of the tree
2246 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
2248 ReadConfiguration(true);
2251 void ShowLinks(TreeServer* Current, userrec* user, int hops)
2253 std::string Parent = TreeRoot->GetName();
2254 if (Current->GetParent())
2256 Parent = Current->GetParent()->GetName();
2258 for (unsigned int q = 0; q < Current->ChildCount(); q++)
2260 ShowLinks(Current->GetChild(q),user,hops+1);
2262 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
2265 int CountLocalServs()
2267 return TreeRoot->ChildCount();
2272 return serverlist.size();
2275 void HandleLinks(char** parameters, int pcnt, userrec* user)
2277 ShowLinks(TreeRoot,user,0);
2278 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
2282 void HandleLusers(char** parameters, int pcnt, userrec* user)
2284 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),this->CountServs());
2285 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
2286 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
2287 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
2288 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
2292 // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
2294 void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
2298 for (int t = 0; t < depth; t++)
2300 matrix[line][t] = ' ';
2302 strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
2304 for (unsigned int q = 0; q < Current->ChildCount(); q++)
2306 ShowMap(Current->GetChild(q),user,depth+2,matrix);
2311 // Ok, prepare to be confused.
2312 // After much mulling over how to approach this, it struck me that
2313 // the 'usual' way of doing a /MAP isnt the best way. Instead of
2314 // keeping track of a ton of ascii characters, and line by line
2315 // under recursion working out where to place them using multiplications
2316 // and divisons, we instead render the map onto a backplane of characters
2317 // (a character matrix), then draw the branches as a series of "L" shapes
2318 // from the nodes. This is not only friendlier on CPU it uses less stack.
2320 void HandleMap(char** parameters, int pcnt, userrec* user)
2322 // This array represents a virtual screen which we will
2323 // "scratch" draw to, as the console device of an irc
2324 // client does not provide for a proper terminal.
2325 char matrix[128][80];
2326 for (unsigned int t = 0; t < 128; t++)
2328 matrix[t][0] = '\0';
2331 // The only recursive bit is called here.
2332 ShowMap(TreeRoot,user,0,matrix);
2333 // Process each line one by one. The algorithm has a limit of
2334 // 128 servers (which is far more than a spanning tree should have
2335 // anyway, so we're ok). This limit can be raised simply by making
2336 // the character matrix deeper, 128 rows taking 10k of memory.
2337 for (int l = 1; l < line; l++)
2339 // scan across the line looking for the start of the
2340 // servername (the recursive part of the algorithm has placed
2341 // the servers at indented positions depending on what they
2343 int first_nonspace = 0;
2344 while (matrix[l][first_nonspace] == ' ')
2349 // Draw the `- (corner) section: this may be overwritten by
2350 // another L shape passing along the same vertical pane, becoming
2351 // a |- (branch) section instead.
2352 matrix[l][first_nonspace] = '-';
2353 matrix[l][first_nonspace-1] = '`';
2355 // Draw upwards until we hit the parent server, causing possibly
2356 // other corners (`-) to become branches (|-)
2357 while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
2359 matrix[l2][first_nonspace-1] = '|';
2363 // dump the whole lot to the user. This is the easy bit, honest.
2364 for (int t = 0; t < line; t++)
2366 WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
2368 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
2372 int HandleSquit(char** parameters, int pcnt, userrec* user)
2374 TreeServer* s = FindServerMask(parameters[0]);
2377 TreeSocket* sock = s->GetSocket();
2380 WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
2381 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
2386 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
2391 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
2396 int HandleRemoteWhois(char** parameters, int pcnt, userrec* user)
2398 if ((user->fd > -1) && (pcnt > 1))
2400 userrec* remote = Srv->FindNick(parameters[1]);
2401 if ((remote) && (remote->fd < 0))
2403 std::deque<std::string> params;
2404 params.push_back(parameters[1]);
2405 DoOneToOne(user->nick,"IDLE",params,remote->server);
2410 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
2411 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
2418 void DoPingChecks(time_t curtime)
2420 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
2422 TreeServer* serv = TreeRoot->GetChild(j);
2423 TreeSocket* sock = serv->GetSocket();
2426 if (curtime >= serv->NextPingTime())
2428 if (serv->AnsweredLastPing())
2430 sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
2431 serv->SetNextPingTime(curtime + 60);
2435 // they didnt answer, boot them
2436 WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
2437 sock->Squit(serv,"Ping timeout");
2446 void AutoConnectServers(time_t curtime)
2448 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2450 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
2452 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
2453 x->NextConnectTime = curtime + x->AutoConnect;
2454 TreeServer* CheckDupe = FindServer(x->Name);
2457 // an autoconnected server is not connected. Check if its time to connect it
2458 WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
2459 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2460 Srv->AddSocket(newsocket);
2466 int HandleVersion(char** parameters, int pcnt, userrec* user)
2468 // we've already checked if pcnt > 0, so this is safe
2469 TreeServer* found = FindServerMask(parameters[0]);
2472 std::string Version = found->GetVersion();
2473 WriteServ(user->fd,"351 %s :%s",user->nick,Version.c_str());
2477 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
2482 int HandleConnect(char** parameters, int pcnt, userrec* user)
2484 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2486 if (Srv->MatchText(x->Name.c_str(),parameters[0]))
2488 TreeServer* CheckDupe = FindServer(x->Name);
2491 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);
2492 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2493 Srv->AddSocket(newsocket);
2498 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());
2503 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
2507 virtual bool HandleStats(char ** parameters, int pcnt, userrec* user)
2509 if (*parameters[0] == 'c')
2511 for (unsigned int i = 0; i < LinkBlocks.size(); i++)
2513 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);
2514 WriteServ(user->fd,"244 %s H * * %s",user->nick,LinkBlocks[i].Name.c_str());
2516 WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
2517 WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
2523 virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
2525 if (command == "CONNECT")
2527 return this->HandleConnect(parameters,pcnt,user);
2529 else if (command == "SQUIT")
2531 return this->HandleSquit(parameters,pcnt,user);
2533 else if (command == "STATS")
2535 return this->HandleStats(parameters,pcnt,user);
2537 else if (command == "MAP")
2539 this->HandleMap(parameters,pcnt,user);
2542 else if (command == "LUSERS")
2544 this->HandleLusers(parameters,pcnt,user);
2547 else if (command == "LINKS")
2549 this->HandleLinks(parameters,pcnt,user);
2552 else if (command == "WHOIS")
2557 return this->HandleRemoteWhois(parameters,pcnt,user);
2560 else if ((command == "VERSION") && (pcnt > 0))
2562 this->HandleVersion(parameters,pcnt,user);
2565 else if (Srv->IsValidModuleCommand(command, pcnt, user))
2567 // this bit of code cleverly routes all module commands
2568 // to all remote severs *automatically* so that modules
2569 // can just handle commands locally, without having
2570 // to have any special provision in place for remote
2571 // commands and linking protocols.
2572 std::deque<std::string> params;
2574 for (int j = 0; j < pcnt; j++)
2576 if (strchr(parameters[j],' '))
2578 params.push_back(":" + std::string(parameters[j]));
2582 params.push_back(std::string(parameters[j]));
2585 DoOneToMany(user->nick,command,params);
2590 virtual void OnGetServerDescription(std::string servername,std::string &description)
2592 TreeServer* s = FindServer(servername);
2595 description = s->GetDesc();
2599 virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
2601 if (source->fd > -1)
2603 std::deque<std::string> params;
2604 params.push_back(dest->nick);
2605 params.push_back(channel->name);
2606 DoOneToMany(source->nick,"INVITE",params);
2610 virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
2612 std::deque<std::string> params;
2613 params.push_back(chan->name);
2614 params.push_back(":"+topic);
2615 DoOneToMany(user->nick,"TOPIC",params);
2618 virtual void OnWallops(userrec* user, std::string text)
2622 std::deque<std::string> params;
2623 params.push_back(":"+text);
2624 DoOneToMany(user->nick,"WALLOPS",params);
2628 virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
2630 if (target_type == TYPE_USER)
2632 userrec* d = (userrec*)dest;
2633 if ((d->fd < 0) && (user->fd > -1))
2635 std::deque<std::string> params;
2637 params.push_back(d->nick);
2638 params.push_back(":"+text);
2639 DoOneToOne(user->nick,"NOTICE",params,d->server);
2646 chanrec *c = (chanrec*)dest;
2647 std::deque<TreeServer*> list;
2648 GetListOfServersForChannel(c,list);
2649 unsigned int ucount = list.size();
2650 for (unsigned int i = 0; i < ucount; i++)
2652 TreeSocket* Sock = list[i]->GetSocket();
2654 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+std::string(c->name)+" :"+text);
2660 virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
2662 if (target_type == TYPE_USER)
2664 // route private messages which are targetted at clients only to the server
2665 // which needs to receive them
2666 userrec* d = (userrec*)dest;
2667 if ((d->fd < 0) && (user->fd > -1))
2669 std::deque<std::string> params;
2671 params.push_back(d->nick);
2672 params.push_back(":"+text);
2673 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
2680 chanrec *c = (chanrec*)dest;
2681 std::deque<TreeServer*> list;
2682 GetListOfServersForChannel(c,list);
2683 unsigned int ucount = list.size();
2684 for (unsigned int i = 0; i < ucount; i++)
2686 TreeSocket* Sock = list[i]->GetSocket();
2688 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+std::string(c->name)+" :"+text);
2694 virtual void OnBackgroundTimer(time_t curtime)
2696 AutoConnectServers(curtime);
2697 DoPingChecks(curtime);
2700 virtual void OnUserJoin(userrec* user, chanrec* channel)
2702 // Only do this for local users
2705 std::deque<std::string> params;
2707 params.push_back(channel->name);
2710 // if the channel has a key, force the join by emulating the key.
2711 params.push_back(channel->key);
2713 if (channel->GetUserCounter() > 1)
2715 // not the first in the channel
2716 DoOneToMany(user->nick,"JOIN",params);
2720 // first in the channel, set up their permissions
2721 // and the channel TS with FJOIN.
2723 snprintf(ts,24,"%lu",(unsigned long)channel->age);
2725 params.push_back(channel->name);
2726 params.push_back(ts);
2727 params.push_back("@"+std::string(user->nick));
2728 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
2733 virtual void OnChangeHost(userrec* user, std::string newhost)
2735 // only occurs for local clients
2736 if (user->registered != 7)
2738 std::deque<std::string> params;
2739 params.push_back(newhost);
2740 DoOneToMany(user->nick,"FHOST",params);
2743 virtual void OnChangeName(userrec* user, std::string gecos)
2745 // only occurs for local clients
2746 if (user->registered != 7)
2748 std::deque<std::string> params;
2749 params.push_back(gecos);
2750 DoOneToMany(user->nick,"FNAME",params);
2753 virtual void OnUserPart(userrec* user, chanrec* channel)
2757 std::deque<std::string> params;
2758 params.push_back(channel->name);
2759 DoOneToMany(user->nick,"PART",params);
2763 virtual void OnUserConnect(userrec* user)
2765 char agestr[MAXBUF];
2768 std::deque<std::string> params;
2769 snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
2770 params.push_back(agestr);
2771 params.push_back(user->nick);
2772 params.push_back(user->host);
2773 params.push_back(user->dhost);
2774 params.push_back(user->ident);
2775 params.push_back("+"+std::string(user->modes));
2776 params.push_back(user->ip);
2777 params.push_back(":"+std::string(user->fullname));
2778 DoOneToMany(Srv->GetServerName(),"NICK",params);
2782 virtual void OnUserQuit(userrec* user, std::string reason)
2784 if ((user->fd > -1) && (user->registered == 7))
2786 std::deque<std::string> params;
2787 params.push_back(":"+reason);
2788 DoOneToMany(user->nick,"QUIT",params);
2792 virtual void OnUserPostNick(userrec* user, std::string oldnick)
2796 std::deque<std::string> params;
2797 params.push_back(user->nick);
2798 DoOneToMany(oldnick,"NICK",params);
2802 virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
2804 if (source->fd > -1)
2806 std::deque<std::string> params;
2807 params.push_back(chan->name);
2808 params.push_back(user->nick);
2809 params.push_back(":"+reason);
2810 DoOneToMany(source->nick,"KICK",params);
2814 virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
2816 std::deque<std::string> params;
2817 params.push_back(dest->nick);
2818 params.push_back(":"+reason);
2819 DoOneToMany(source->nick,"KILL",params);
2822 virtual void OnRehash(std::string parameter)
2824 if (parameter != "")
2826 std::deque<std::string> params;
2827 params.push_back(parameter);
2828 DoOneToMany(Srv->GetServerName(),"REHASH",params);
2830 if (Srv->MatchText(Srv->GetServerName(),parameter))
2832 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
2833 Srv->RehashServer();
2836 ReadConfiguration(false);
2839 // note: the protocol does not allow direct umode +o except
2840 // via NICK with 8 params. sending OPERTYPE infers +o modechange
2842 virtual void OnOper(userrec* user, std::string opertype)
2846 std::deque<std::string> params;
2847 params.push_back(opertype);
2848 DoOneToMany(user->nick,"OPERTYPE",params);
2852 void OnLine(userrec* source, std::string host, bool adding, char linetype, long duration, std::string reason)
2854 if (source->fd > -1)
2857 snprintf(type,8,"%cLINE",linetype);
2858 std::string stype = type;
2861 char sduration[MAXBUF];
2862 snprintf(sduration,MAXBUF,"%ld",duration);
2863 std::deque<std::string> params;
2864 params.push_back(host);
2865 params.push_back(sduration);
2866 params.push_back(":"+reason);
2867 DoOneToMany(source->nick,stype,params);
2871 std::deque<std::string> params;
2872 params.push_back(host);
2873 DoOneToMany(source->nick,stype,params);
2878 virtual void OnAddGLine(long duration, userrec* source, std::string reason, std::string hostmask)
2880 OnLine(source,hostmask,true,'G',duration,reason);
2883 virtual void OnAddZLine(long duration, userrec* source, std::string reason, std::string ipmask)
2885 OnLine(source,ipmask,true,'Z',duration,reason);
2888 virtual void OnAddQLine(long duration, userrec* source, std::string reason, std::string nickmask)
2890 OnLine(source,nickmask,true,'Q',duration,reason);
2893 virtual void OnAddELine(long duration, userrec* source, std::string reason, std::string hostmask)
2895 OnLine(source,hostmask,true,'E',duration,reason);
2898 virtual void OnDelGLine(userrec* source, std::string hostmask)
2900 OnLine(source,hostmask,false,'G',0,"");
2903 virtual void OnDelZLine(userrec* source, std::string ipmask)
2905 OnLine(source,ipmask,false,'Z',0,"");
2908 virtual void OnDelQLine(userrec* source, std::string nickmask)
2910 OnLine(source,nickmask,false,'Q',0,"");
2913 virtual void OnDelELine(userrec* source, std::string hostmask)
2915 OnLine(source,hostmask,false,'E',0,"");
2918 virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
2920 if ((user->fd > -1) && (user->registered == 7))
2922 if (target_type == TYPE_USER)
2924 userrec* u = (userrec*)dest;
2925 std::deque<std::string> params;
2926 params.push_back(u->nick);
2927 params.push_back(text);
2928 DoOneToMany(user->nick,"MODE",params);
2932 chanrec* c = (chanrec*)dest;
2933 std::deque<std::string> params;
2934 params.push_back(c->name);
2935 params.push_back(text);
2936 DoOneToMany(user->nick,"MODE",params);
2941 virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
2943 TreeSocket* s = (TreeSocket*)opaque;
2946 if (target_type == TYPE_USER)
2948 userrec* u = (userrec*)target;
2949 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
2953 chanrec* c = (chanrec*)target;
2954 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
2959 virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, std::string extname, std::string extdata)
2961 TreeSocket* s = (TreeSocket*)opaque;
2964 if (target_type == TYPE_USER)
2966 userrec* u = (userrec*)target;
2967 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+u->nick+" "+extname+" :"+extdata);
2971 chanrec* c = (chanrec*)target;
2972 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+c->name+" "+extname+" :"+extdata);
2977 virtual ~ModuleSpanningTree()
2981 virtual Version GetVersion()
2983 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
2988 class ModuleSpanningTreeFactory : public ModuleFactory
2991 ModuleSpanningTreeFactory()
2995 ~ModuleSpanningTreeFactory()
2999 virtual Module * CreateModule(Server* Me)
3001 TreeProtocolModule = new ModuleSpanningTree(Me);
3002 return TreeProtocolModule;
3008 extern "C" void * init_module( void )
3010 return new ModuleSpanningTreeFactory;