]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree.cpp
Was using OnUserPre* when i wanted to use OnUser*, which meant that remote servers...
[user/henk/code/inspircd.git] / src / modules / m_spanningtree.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
6  *                       E-mail:
7  *                <brain@chatspike.net>
8  *                <Craig@chatspike.net>
9  *     
10  * Written by Craig Edwards, Craig McLure, and others.
11  * This program is free but copyrighted software; see
12  *            the file COPYING for details.
13  *
14  * ---------------------------------------------------
15  */
16
17 /* $ModDesc: Povides a spanning tree server link protocol */
18
19 using namespace std;
20
21 #include <stdio.h>
22 #include <vector>
23 #include <deque>
24 #include "globals.h"
25 #include "inspircd_config.h"
26 #ifdef GCC3
27 #include <ext/hash_map>
28 #else
29 #include <hash_map>
30 #endif
31 #include "users.h"
32 #include "channels.h"
33 #include "modules.h"
34 #include "commands.h"
35 #include "socket.h"
36 #include "helperfuncs.h"
37 #include "inspircd.h"
38 #include "inspstring.h"
39 #include "hashcomp.h"
40 #include "message.h"
41 #include "xline.h"
42 #include "typedefs.h"
43 #include "cull_list.h"
44 #include "aes.h"
45
46 #ifdef GCC3
47 #define nspace __gnu_cxx
48 #else
49 #define nspace std
50 #endif
51
52 /*
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:
56  *
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
61  *
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.
71  */
72
73 class ModuleSpanningTree;
74 static ModuleSpanningTree* TreeProtocolModule;
75
76 extern ServerConfig* Config;
77
78 extern std::vector<Module*> modules;
79 extern std::vector<ircd_module*> factory;
80 extern int MODCOUNT;
81
82 /* Any socket can have one of five states at any one time.
83  * The LISTENER state indicates a socket which is listening
84  * for connections. It cannot receive data itself, only incoming
85  * sockets.
86  * The CONNECTING state indicates an outbound socket which is
87  * waiting to be writeable.
88  * The WAIT_AUTH_1 state indicates the socket is outbound and
89  * has successfully connected, but has not yet sent and received
90  * SERVER strings.
91  * The WAIT_AUTH_2 state indicates that the socket is inbound
92  * (allocated by a LISTENER) but has not yet sent and received
93  * SERVER strings.
94  * The CONNECTED state represents a fully authorized, fully
95  * connected server.
96  */
97 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
98
99 /* We need to import these from the core for use in netbursts */
100 extern user_hash clientlist;
101 extern chan_hash chanlist;
102
103 /* Foward declarations */
104 class TreeServer;
105 class TreeSocket;
106
107 /* This variable represents the root of the server tree
108  * (for all intents and purposes, it's us)
109  */
110 TreeServer *TreeRoot;
111
112 Server* Srv;
113
114 /* This hash_map holds the hash equivalent of the server
115  * tree, used for rapid linear lookups.
116  */
117 typedef nspace::hash_map<std::string, TreeServer*> server_hash;
118 server_hash serverlist;
119
120 /* More forward declarations */
121 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> &params, std::string target);
122 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> &params, std::string omit);
123 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> &params);
124 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, std::string command, std::deque<std::string> &params);
125 void ReadConfiguration(bool rebind);
126
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;
138
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.
152  */
153
154 class TreeServer
155 {
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 */
167         
168  public:
169
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.
172          */
173         TreeServer()
174         {
175                 Parent = NULL;
176                 ServerName = "";
177                 ServerDesc = "";
178                 VersionString = "";
179                 UserCount = OperCount = 0;
180                 VersionString = Srv->GetVersion();
181         }
182
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.
186          */
187         TreeServer(std::string Name, std::string Desc) : ServerName(Name), ServerDesc(Desc)
188         {
189                 Parent = NULL;
190                 VersionString = "";
191                 UserCount = OperCount = 0;
192                 VersionString = Srv->GetVersion();
193                 Route = NULL;
194                 Socket = NULL; /* Fix by brain */
195                 AddHashEntry();
196         }
197
198         /* When we create a new server, we call this constructor to initialize it.
199          * This constructor initializes the server's Route and Parent, and sets up
200          * its ping counters so that it will be pinged one minute from now.
201          */
202         TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name), ServerDesc(Desc), Socket(Sock)
203         {
204                 VersionString = "";
205                 UserCount = OperCount = 0;
206                 this->SetNextPingTime(time(NULL) + 120);
207                 this->SetPingFlag();
208
209                 /* find the 'route' for this server (e.g. the one directly connected
210                  * to the local server, which we can use to reach it)
211                  *
212                  * In the following example, consider we have just added a TreeServer
213                  * class for server G on our network, of which we are server A.
214                  * To route traffic to G (marked with a *) we must send the data to
215                  * B (marked with a +) so this algorithm initializes the 'Route'
216                  * value to point at whichever server traffic must be routed through
217                  * to get here. If we were to try this algorithm with server B,
218                  * the Route pointer would point at its own object ('this').
219                  *
220                  *              A
221                  *             / \
222                  *          + B   C
223                  *           / \   \
224                  *          D   E   F
225                  *         /         \
226                  *      * G           H
227                  *
228                  * We only run this algorithm when a server is created, as
229                  * the routes remain constant while ever the server exists, and
230                  * do not need to be re-calculated.
231                  */
232
233                 Route = Above;
234                 if (Route == TreeRoot)
235                 {
236                         Route = this;
237                 }
238                 else
239                 {
240                         while (this->Route->GetParent() != TreeRoot)
241                         {
242                                 this->Route = Route->GetParent();
243                         }
244                 }
245
246                 /* Because recursive code is slow and takes a lot of resources,
247                  * we store two representations of the server tree. The first
248                  * is a recursive structure where each server references its
249                  * children and its parent, which is used for netbursts and
250                  * netsplits to dump the whole dataset to the other server,
251                  * and the second is used for very fast lookups when routing
252                  * messages and is instead a hash_map, where each item can
253                  * be referenced by its server name. The AddHashEntry()
254                  * call below automatically inserts each TreeServer class
255                  * into the hash_map as it is created. There is a similar
256                  * maintainance call in the destructor to tidy up deleted
257                  * servers.
258                  */
259
260                 this->AddHashEntry();
261         }
262
263         /* This method is used to add the structure to the
264          * hash_map for linear searches. It is only called
265          * by the constructors.
266          */
267         void AddHashEntry()
268         {
269                 server_hash::iterator iter;
270                 iter = serverlist.find(this->ServerName);
271                 if (iter == serverlist.end())
272                         serverlist[this->ServerName] = this;
273         }
274
275         /* This method removes the reference to this object
276          * from the hash_map which is used for linear searches.
277          * It is only called by the default destructor.
278          */
279         void DelHashEntry()
280         {
281                 server_hash::iterator iter;
282                 iter = serverlist.find(this->ServerName);
283                 if (iter != serverlist.end())
284                         serverlist.erase(iter);
285         }
286
287         /* These accessors etc should be pretty self-
288          * explanitory.
289          */
290
291         TreeServer* GetRoute()
292         {
293                 return Route;
294         }
295
296         std::string GetName()
297         {
298                 return ServerName;
299         }
300
301         std::string GetDesc()
302         {
303                 return ServerDesc;
304         }
305
306         std::string GetVersion()
307         {
308                 return VersionString;
309         }
310
311         void SetNextPingTime(time_t t)
312         {
313                 this->NextPing = t;
314                 LastPingWasGood = false;
315         }
316
317         time_t NextPingTime()
318         {
319                 return NextPing;
320         }
321
322         bool AnsweredLastPing()
323         {
324                 return LastPingWasGood;
325         }
326
327         void SetPingFlag()
328         {
329                 LastPingWasGood = true;
330         }
331
332         int GetUserCount()
333         {
334                 return UserCount;
335         }
336
337         void AddUserCount()
338         {
339                 UserCount++;
340         }
341
342         void DelUserCount()
343         {
344                 UserCount--;
345         }
346
347         int GetOperCount()
348         {
349                 return OperCount;
350         }
351
352         TreeSocket* GetSocket()
353         {
354                 return Socket;
355         }
356
357         TreeServer* GetParent()
358         {
359                 return Parent;
360         }
361
362         void SetVersion(std::string Version)
363         {
364                 VersionString = Version;
365         }
366
367         unsigned int ChildCount()
368         {
369                 return Children.size();
370         }
371
372         TreeServer* GetChild(unsigned int n)
373         {
374                 if (n < Children.size())
375                 {
376                         /* Make sure they  cant request
377                          * an out-of-range object. After
378                          * all we know what these programmer
379                          * types are like *grin*.
380                          */
381                         return Children[n];
382                 }
383                 else
384                 {
385                         return NULL;
386                 }
387         }
388
389         void AddChild(TreeServer* Child)
390         {
391                 Children.push_back(Child);
392         }
393
394         bool DelChild(TreeServer* Child)
395         {
396                 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
397                 {
398                         if (*a == Child)
399                         {
400                                 Children.erase(a);
401                                 return true;
402                         }
403                 }
404                 return false;
405         }
406
407         /* Removes child nodes of this node, and of that node, etc etc.
408          * This is used during netsplits to automatically tidy up the
409          * server tree. It is slow, we don't use it for much else.
410          */
411         bool Tidy()
412         {
413                 bool stillchildren = true;
414                 while (stillchildren)
415                 {
416                         stillchildren = false;
417                         for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
418                         {
419                                 TreeServer* s = (TreeServer*)*a;
420                                 s->Tidy();
421                                 Children.erase(a);
422                                 delete s;
423                                 stillchildren = true;
424                                 break;
425                         }
426                 }
427                 return true;
428         }
429
430         ~TreeServer()
431         {
432                 /* We'd better tidy up after ourselves, eh? */
433                 this->DelHashEntry();
434         }
435 };
436
437 /* The Link class might as well be a struct,
438  * but this is C++ and we don't believe in structs (!).
439  * It holds the entire information of one <link>
440  * tag from the main config file. We maintain a list
441  * of them, and populate the list on rehash/load.
442  */
443
444 class Link
445 {
446  public:
447          std::string Name;
448          std::string IPAddr;
449          int Port;
450          std::string SendPass;
451          std::string RecvPass;
452          unsigned long AutoConnect;
453          time_t NextConnectTime;
454          std::string EncryptionKey;
455 };
456
457 /* The usual stuff for inspircd modules,
458  * plus the vector of Link classes which we
459  * use to store the <link> tags from the config
460  * file.
461  */
462 ConfigReader *Conf;
463 std::vector<Link> LinkBlocks;
464
465 /* Yay for fast searches!
466  * This is hundreds of times faster than recursion
467  * or even scanning a linked list, especially when
468  * there are more than a few servers to deal with.
469  * (read as: lots).
470  */
471 TreeServer* FindServer(std::string ServerName)
472 {
473         server_hash::iterator iter;
474         iter = serverlist.find(ServerName);
475         if (iter != serverlist.end())
476         {
477                 return iter->second;
478         }
479         else
480         {
481                 return NULL;
482         }
483 }
484
485 /* Returns the locally connected server we must route a
486  * message through to reach server 'ServerName'. This
487  * only applies to one-to-one and not one-to-many routing.
488  * See the comments for the constructor of TreeServer
489  * for more details.
490  */
491 TreeServer* BestRouteTo(std::string ServerName)
492 {
493         if (ServerName.c_str() == TreeRoot->GetName())
494                 return NULL;
495         TreeServer* Found = FindServer(ServerName);
496         if (Found)
497         {
498                 return Found->GetRoute();
499         }
500         else
501         {
502                 return NULL;
503         }
504 }
505
506 /* Find the first server matching a given glob mask.
507  * Theres no find-using-glob method of hash_map [awwww :-(]
508  * so instead, we iterate over the list using an iterator
509  * and match each one until we get a hit. Yes its slow,
510  * deal with it.
511  */
512 TreeServer* FindServerMask(std::string ServerName)
513 {
514         for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
515         {
516                 if (Srv->MatchText(i->first,ServerName))
517                         return i->second;
518         }
519         return NULL;
520 }
521
522 /* A convenient wrapper that returns true if a server exists */
523 bool IsServer(std::string ServerName)
524 {
525         return (FindServer(ServerName) != NULL);
526 }
527
528 /* Every SERVER connection inbound or outbound is represented by
529  * an object of type TreeSocket.
530  * TreeSockets, being inherited from InspSocket, can be tied into
531  * the core socket engine, and we cn therefore receive activity events
532  * for them, just like activex objects on speed. (yes really, that
533  * is a technical term!) Each of these which relates to a locally
534  * connected server is assocated with it, by hooking it onto a
535  * TreeSocket class using its constructor. In this way, we can
536  * maintain a list of servers, some of which are directly connected,
537  * some of which are not.
538  */
539
540 class TreeSocket : public InspSocket
541 {
542         std::string myhost;
543         std::string in_buffer;
544         ServerState LinkState;
545         std::string InboundServerName;
546         std::string InboundDescription;
547         int num_lost_users;
548         int num_lost_servers;
549         time_t NextPing;
550         bool LastPingWasGood;
551         bool bursting;
552         AES* ctx_in;
553         AES* ctx_out;
554         unsigned int keylength;
555         
556  public:
557
558         /* Because most of the I/O gubbins are encapsulated within
559          * InspSocket, we just call the superclass constructor for
560          * most of the action, and append a few of our own values
561          * to it.
562          */
563         TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
564                 : InspSocket(host, port, listening, maxtime)
565         {
566                 myhost = host;
567                 this->LinkState = LISTENER;
568                 this->ctx_in = NULL;
569                 this->ctx_out = NULL;
570         }
571
572         TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
573                 : InspSocket(host, port, listening, maxtime)
574         {
575                 myhost = ServerName;
576                 this->LinkState = CONNECTING;
577                 this->ctx_in = NULL;
578                 this->ctx_out = NULL;
579         }
580
581         /* When a listening socket gives us a new file descriptor,
582          * we must associate it with a socket without creating a new
583          * connection. This constructor is used for this purpose.
584          */
585         TreeSocket(int newfd, char* ip)
586                 : InspSocket(newfd, ip)
587         {
588                 this->LinkState = WAIT_AUTH_1;
589                 this->ctx_in = NULL;
590                 this->ctx_out = NULL;
591                 this->SendCapabilities();
592         }
593
594         ~TreeSocket()
595         {
596                 if (ctx_in)
597                         delete ctx_in;
598                 if (ctx_out)
599                         delete ctx_out;
600         }
601
602         void InitAES(std::string key,std::string SName)
603         {
604                 if (key == "")
605                         return;
606
607                 ctx_in = new AES();
608                 ctx_out = new AES();
609                 log(DEBUG,"Initialized AES key %s",key.c_str());
610                 // key must be 16, 24, 32 etc bytes (multiple of 8)
611                 keylength = key.length();
612                 if (!(keylength == 16 || keylength == 24 || keylength == 32))
613                 {
614                         WriteOpers("*** \2ERROR\2: Key length for encryptionkey is not 16, 24 or 32 bytes in length!");
615                         log(DEBUG,"Key length not 16, 24 or 32 characters!");
616                 }
617                 else
618                 {
619                         WriteOpers("*** \2AES\2: Initialized %d bit encryption to server %s",keylength*8,SName.c_str());
620                         ctx_in->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\
621                                 \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);
622                         ctx_out->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\
623                                 \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);
624                 }
625         }
626         
627         /* When an outbound connection finishes connecting, we receive
628          * this event, and must send our SERVER string to the other
629          * side. If the other side is happy, as outlined in the server
630          * to server docs on the inspircd.org site, the other side
631          * will then send back its own server string.
632          */
633         virtual bool OnConnected()
634         {
635                 if (this->LinkState == CONNECTING)
636                 {
637                         Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
638                         /* we do not need to change state here. */
639                         for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
640                         {
641                                 if (x->Name == this->myhost)
642                                 {
643                                         this->SendCapabilities();
644                                         if (x->EncryptionKey != "")
645                                         {
646                                                 if (!(x->EncryptionKey.length() == 16 || x->EncryptionKey.length() == 24 || x->EncryptionKey.length() == 32))
647                                                 {
648                                                         WriteOpers("\2WARNING\2: Your encryption key is NOT 16, 24 or 32 characters in length, encryption will \2NOT\2 be enabled.");
649                                                 }
650                                                 else
651                                                 {
652                                                         this->WriteLine("AES "+Srv->GetServerName());
653                                                         this->InitAES(x->EncryptionKey,x->Name);
654                                                 }
655                                         }
656                                         /* found who we're supposed to be connecting to, send the neccessary gubbins. */
657                                         this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
658                                         return true;
659                                 }
660                         }
661                 }
662                 /* There is a (remote) chance that between the /CONNECT and the connection
663                  * being accepted, some muppet has removed the <link> block and rehashed.
664                  * If that happens the connection hangs here until it's closed. Unlikely
665                  * and rather harmless.
666                  */
667                 return true;
668         }
669         
670         virtual void OnError(InspSocketError e)
671         {
672                 /* We don't handle this method, because all our
673                  * dirty work is done in OnClose() (see below)
674                  * which is still called on error conditions too.
675                  */
676         }
677
678         virtual int OnDisconnect()
679         {
680                 /* For the same reason as above, we don't
681                  * handle OnDisconnect()
682                  */
683                 return true;
684         }
685
686         /* Recursively send the server tree with distances as hops.
687          * This is used during network burst to inform the other server
688          * (and any of ITS servers too) of what servers we know about.
689          * If at any point any of these servers already exist on the other
690          * end, our connection may be terminated. The hopcounts given
691          * by this function are relative, this doesn't matter so long as
692          * they are all >1, as all the remote servers re-calculate them
693          * to be relative too, with themselves as hop 0.
694          */
695         void SendServers(TreeServer* Current, TreeServer* s, int hops)
696         {
697                 char command[1024];
698                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
699                 {
700                         TreeServer* recursive_server = Current->GetChild(q);
701                         if (recursive_server != s)
702                         {
703                                 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
704                                 this->WriteLine(command);
705                                 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
706                                 /* down to next level */
707                                 this->SendServers(recursive_server, s, hops+1);
708                         }
709                 }
710         }
711
712         std::string MyCapabilities()
713         {
714                 ServerConfig* Config = Srv->GetConfig();
715                 std::vector<std::string> modlist;
716                 std::string capabilities = "";
717
718                 for (int i = 0; i <= MODCOUNT; i++)
719                 {
720                         if ((modules[i]->GetVersion().Flags & VF_STATIC) || (modules[i]->GetVersion().Flags & VF_COMMON))
721                                 modlist.push_back(Config->module_names[i]);
722                 }
723                 sort(modlist.begin(),modlist.end());
724                 for (unsigned int i = 0; i < modlist.size(); i++)
725                 {
726                         if (i)
727                                 capabilities = capabilities + ",";
728                         capabilities = capabilities + modlist[i];
729                 }
730                 return capabilities;
731         }
732         
733         void SendCapabilities()
734         {
735                 this->WriteLine("CAPAB "+MyCapabilities());
736         }
737
738         bool Capab(std::deque<std::string> params)
739         {
740                 if (params.size() != 1)
741                 {
742                         this->WriteLine("ERROR :Invalid number of parameters for CAPAB");
743                         return false;
744                 }
745                 if (params[0] != this->MyCapabilities())
746                 {
747                         std::string quitserver = this->myhost;
748                         if (this->InboundServerName != "")
749                         {
750                                 quitserver = this->InboundServerName;
751                         }
752                         WriteOpers("*** \2ERROR\2: Server '%s' does not have the same set of modules loaded, cannot link!",quitserver.c_str());
753                         WriteOpers("*** Our networked module set is: '%s'",this->MyCapabilities().c_str());
754                         WriteOpers("*** Other server's networked module set is: '%s'",params[0].c_str());
755                         WriteOpers("*** These lists must match exactly on both servers. Please correct these errors, and try again.");
756                         this->WriteLine("ERROR :CAPAB mismatch; My capabilities: '"+this->MyCapabilities()+"'");
757                         return false;
758                 }
759                 return true;
760         }
761
762         /* This function forces this server to quit, removing this server
763          * and any users on it (and servers and users below that, etc etc).
764          * It's very slow and pretty clunky, but luckily unless your network
765          * is having a REAL bad hair day, this function shouldnt be called
766          * too many times a month ;-)
767          */
768         void SquitServer(TreeServer* Current, CullList* Goners)
769         {
770                 /* recursively squit the servers attached to 'Current'.
771                  * We're going backwards so we don't remove users
772                  * while we still need them ;)
773                  */
774                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
775                 {
776                         TreeServer* recursive_server = Current->GetChild(q);
777                         this->SquitServer(recursive_server,Goners);
778                 }
779                 /* Now we've whacked the kids, whack self */
780                 num_lost_servers++;
781                 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
782                 {
783                         if (!strcasecmp(u->second->server,Current->GetName().c_str()))
784                         {
785                                 std::string qreason = Current->GetName()+" "+std::string(Srv->GetServerName());
786                                 Goners->AddItem(u->second,qreason);
787                                 num_lost_users++;
788                         }
789                 }
790         }
791
792         /* This is a wrapper function for SquitServer above, which
793          * does some validation first and passes on the SQUIT to all
794          * other remaining servers.
795          */
796         void Squit(TreeServer* Current,std::string reason)
797         {
798                 if ((Current) && (Current != TreeRoot))
799                 {
800                         std::deque<std::string> params;
801                         params.push_back(Current->GetName());
802                         params.push_back(":"+reason);
803                         DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
804                         if (Current->GetParent() == TreeRoot)
805                         {
806                                 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
807                         }
808                         else
809                         {
810                                 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
811                         }
812                         num_lost_servers = 0;
813                         num_lost_users = 0;
814                         CullList* Goners = new CullList();
815                         SquitServer(Current, Goners);
816                         Goners->Apply();
817                         Current->Tidy();
818                         Current->GetParent()->DelChild(Current);
819                         delete Current;
820                         delete Goners;
821                         WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
822                 }
823                 else
824                 {
825                         log(DEFAULT,"Squit from unknown server");
826                 }
827         }
828
829         /* FMODE command */
830         bool ForceMode(std::string source, std::deque<std::string> params)
831         {
832                 userrec* who = new userrec;
833                 who->fd = FD_MAGIC_NUMBER;
834                 if (params.size() < 2)
835                         return true;
836                 char* modelist[255];
837                 for (unsigned int q = 0; q < params.size(); q++)
838                 {
839                         modelist[q] = (char*)params[q].c_str();
840                 }
841                 Srv->SendMode(modelist,params.size(),who);
842                 DoOneToAllButSender(source,"FMODE",params,source);
843                 delete who;
844                 return true;
845         }
846
847         /* FTOPIC command */
848         bool ForceTopic(std::string source, std::deque<std::string> params)
849         {
850                 if (params.size() != 4)
851                         return true;
852                 std::string channel = params[0];
853                 time_t ts = atoi(params[1].c_str());
854                 std::string setby = params[2];
855                 std::string topic = params[3];
856
857                 chanrec* c = Srv->FindChannel(channel);
858                 if (c)
859                 {
860                         if ((ts >= c->topicset) || (!*c->topic))
861                         {
862                                 std::string oldtopic = c->topic;
863                                 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
864                                 strlcpy(c->setby,setby.c_str(),NICKMAX);
865                                 c->topicset = ts;
866                                 /* if the topic text is the same as the current topic,
867                                  * dont bother to send the TOPIC command out, just silently
868                                  * update the set time and set nick.
869                                  */
870                                 if (oldtopic != topic)
871                                         WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
872                         }
873                         
874                 }
875                 
876                 /* all done, send it on its way */
877                 params[3] = ":" + params[3];
878                 DoOneToAllButSender(source,"FTOPIC",params,source);
879
880                 return true;
881         }
882
883         /* FJOIN, similar to unreal SJOIN */
884         bool ForceJoin(std::string source, std::deque<std::string> params)
885         {
886                 if (params.size() < 3)
887                         return true;
888
889                 char first[MAXBUF];
890                 char modestring[MAXBUF];
891                 char* mode_users[127];
892                 mode_users[0] = first;
893                 mode_users[1] = modestring;
894                 strcpy(mode_users[1],"+");
895                 unsigned int modectr = 2;
896                 
897                 userrec* who = NULL;
898                 std::string channel = params[0];
899                 time_t TS = atoi(params[1].c_str());
900                 char* key = "";
901                 
902                 chanrec* chan = Srv->FindChannel(channel);
903                 if (chan)
904                 {
905                         key = chan->key;
906                 }
907                 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
908
909                 /* default is a high value, which if we dont have this
910                  * channel will let the other side apply their modes.
911                  */
912                 time_t ourTS = time(NULL)+600;
913                 chanrec* us = Srv->FindChannel(channel);
914                 if (us)
915                 {
916                         ourTS = us->age;
917                 }
918
919                 log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
920
921                 /* do this first, so our mode reversals are correctly received by other servers
922                  * if there is a TS collision.
923                  */
924                 DoOneToAllButSender(source,"FJOIN",params,source);
925                 
926                 for (unsigned int usernum = 2; usernum < params.size(); usernum++)
927                 {
928                         /* process one channel at a time, applying modes. */
929                         char* usr = (char*)params[usernum].c_str();
930                         /* Safety check just to make sure someones not sent us an FJOIN full of spaces
931                          * (is this even possible?) */
932                         if (usr && *usr)
933                         {
934                                 char permissions = *usr;
935                                 switch (permissions)
936                                 {
937                                         case '@':
938                                                 usr++;
939                                                 mode_users[modectr++] = usr;
940                                                 strlcat(modestring,"o",MAXBUF);
941                                         break;
942                                         case '%':
943                                                 usr++;
944                                                 mode_users[modectr++] = usr;
945                                                 strlcat(modestring,"h",MAXBUF);
946                                         break;
947                                         case '+':
948                                                 usr++;
949                                                 mode_users[modectr++] = usr;
950                                                 strlcat(modestring,"v",MAXBUF);
951                                         break;
952                                 }
953                                 who = Srv->FindNick(usr);
954                                 if (who)
955                                 {
956                                         Srv->JoinUserToChannel(who,channel,key);
957                                         if (modectr >= (MAXMODES-1))
958                                         {
959                                                 /* theres a mode for this user. push them onto the mode queue, and flush it
960                                                  * if there are more than MAXMODES to go.
961                                                  */
962                                                 if ((ourTS >= TS) || (Srv->IsUlined(who->server)))
963                                                 {
964                                                         /* We also always let u-lined clients win, no matter what the TS value */
965                                                         log(DEBUG,"Our our channel newer than theirs, accepting their modes");
966                                                         Srv->SendMode(mode_users,modectr,who);
967                                                 }
968                                                 else
969                                                 {
970                                                         log(DEBUG,"Their channel newer than ours, bouncing their modes");
971                                                         /* bouncy bouncy! */
972                                                         std::deque<std::string> params;
973                                                         /* modes are now being UNSET... */
974                                                         *mode_users[1] = '-';
975                                                         for (unsigned int x = 0; x < modectr; x++)
976                                                         {
977                                                                 params.push_back(mode_users[x]);
978                                                         }
979                                                         // tell everyone to bounce the modes. bad modes, bad!
980                                                         DoOneToMany(Srv->GetServerName(),"FMODE",params);
981                                                 }
982                                                 strcpy(mode_users[1],"+");
983                                                 modectr = 2;
984                                         }
985                                 }
986                         }
987                 }
988                 /* there werent enough modes built up to flush it during FJOIN,
989                  * or, there are a number left over. flush them out.
990                  */
991                 if ((modectr > 2) && (who))
992                 {
993                         if (ourTS >= TS)
994                         {
995                                 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
996                                 Srv->SendMode(mode_users,modectr,who);
997                         }
998                         else
999                         {
1000                                 log(DEBUG,"Their channel newer than ours, bouncing their modes");
1001                                 std::deque<std::string> params;
1002                                 *mode_users[1] = '-';
1003                                 for (unsigned int x = 0; x < modectr; x++)
1004                                 {
1005                                         params.push_back(mode_users[x]);
1006                                 }
1007                                 DoOneToMany(Srv->GetServerName(),"FMODE",params);
1008                         }
1009                 }
1010                 return true;
1011         }
1012
1013         /* NICK command */
1014         bool IntroduceClient(std::string source, std::deque<std::string> params)
1015         {
1016                 if (params.size() < 8)
1017                         return true;
1018                 // NICK age nick host dhost ident +modes ip :gecos
1019                 //       0   1    2    3      4     5    6   7
1020                 std::string nick = params[1];
1021                 std::string host = params[2];
1022                 std::string dhost = params[3];
1023                 std::string ident = params[4];
1024                 time_t age = atoi(params[0].c_str());
1025                 std::string modes = params[5];
1026                 while (*(modes.c_str()) == '+')
1027                 {
1028                         char* m = (char*)modes.c_str();
1029                         m++;
1030                         modes = m;
1031                 }
1032                 std::string ip = params[6];
1033                 std::string gecos = params[7];
1034                 char* tempnick = (char*)nick.c_str();
1035                 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
1036                 
1037                 user_hash::iterator iter;
1038                 iter = clientlist.find(tempnick);
1039                 if (iter != clientlist.end())
1040                 {
1041                         // nick collision
1042                         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);
1043                         this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
1044                         return true;
1045                 }
1046
1047                 clientlist[tempnick] = new userrec();
1048                 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
1049                 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
1050                 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
1051                 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
1052                 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
1053                 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
1054                 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
1055                 clientlist[tempnick]->registered = 7;
1056                 clientlist[tempnick]->signon = age;
1057                 strlcpy(clientlist[tempnick]->modes, modes.c_str(),53);
1058                 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
1059
1060                 ucrec a;
1061                 a.channel = NULL;
1062                 a.uc_modes = 0;
1063                 for (int i = 0; i < MAXCHANS; i++)
1064                         clientlist[tempnick]->chans.push_back(a);
1065
1066                 if (!this->bursting)
1067                 {
1068                         WriteOpers("*** Client connecting at %s: %s!%s@%s [%s]",clientlist[tempnick]->server,clientlist[tempnick]->nick,clientlist[tempnick]->ident,clientlist[tempnick]->host,clientlist[tempnick]->ip);
1069                 }
1070                 params[7] = ":" + params[7];
1071                 DoOneToAllButSender(source,"NICK",params,source);
1072
1073                 // Increment the Source Servers User Count..
1074                 TreeServer* SourceServer = FindServer(source);
1075                 if (SourceServer) {
1076                         SourceServer->AddUserCount();
1077                 }
1078
1079                 return true;
1080         }
1081
1082         /* Send one or more FJOINs for a channel of users.
1083          * If the length of a single line is more than 480-NICKMAX
1084          * in length, it is split over multiple lines.
1085          */
1086         void SendFJoins(TreeServer* Current, chanrec* c)
1087         {
1088                 log(DEBUG,"Sending FJOINs to other server for %s",c->name);
1089                 char list[MAXBUF];
1090                 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1091                 std::map<char*,char*> *ulist = c->GetUsers();
1092                 for (std::map<char*,char*>::iterator i = ulist->begin(); i != ulist->end(); i++)
1093                 {
1094                         char* o = i->second;
1095                         userrec* otheruser = (userrec*)o;
1096                         strlcat(list," ",MAXBUF);
1097                         strlcat(list,cmode(otheruser,c),MAXBUF);
1098                         strlcat(list,otheruser->nick,MAXBUF);
1099                         if (strlen(list)>(480-NICKMAX))
1100                         {
1101                                 log(DEBUG,"FJOIN line wrapped");
1102                                 this->WriteLine(list);
1103                                 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1104                         }
1105                 }
1106                 if (list[strlen(list)-1] != ':')
1107                 {
1108                         log(DEBUG,"Final FJOIN line");
1109                         this->WriteLine(list);
1110                 }
1111         }
1112
1113         /* Send G, Q, Z and E lines */
1114         void SendXLines(TreeServer* Current)
1115         {
1116                 char data[MAXBUF];
1117                 /* Yes, these arent too nice looking, but they get the job done */
1118                 for (std::vector<ZLine>::iterator i = zlines.begin(); i != zlines.end(); i++)
1119                 {
1120                         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);
1121                         this->WriteLine(data);
1122                 }
1123                 for (std::vector<QLine>::iterator i = qlines.begin(); i != qlines.end(); i++)
1124                 {
1125                         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);
1126                         this->WriteLine(data);
1127                 }
1128                 for (std::vector<GLine>::iterator i = glines.begin(); i != glines.end(); i++)
1129                 {
1130                         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);
1131                         this->WriteLine(data);
1132                 }
1133                 for (std::vector<ELine>::iterator i = elines.begin(); i != elines.end(); i++)
1134                 {
1135                         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);
1136                         this->WriteLine(data);
1137                 }
1138                 for (std::vector<ZLine>::iterator i = pzlines.begin(); i != pzlines.end(); i++)
1139                 {
1140                         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);
1141                         this->WriteLine(data);
1142                 }
1143                 for (std::vector<QLine>::iterator i = pqlines.begin(); i != pqlines.end(); i++)
1144                 {
1145                         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);
1146                         this->WriteLine(data);
1147                 }
1148                 for (std::vector<GLine>::iterator i = pglines.begin(); i != pglines.end(); i++)
1149                 {
1150                         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);
1151                         this->WriteLine(data);
1152                 }
1153                 for (std::vector<ELine>::iterator i = pelines.begin(); i != pelines.end(); i++)
1154                 {
1155                         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);
1156                         this->WriteLine(data);
1157                 }
1158         }
1159
1160         /* Send channel modes and topics */
1161         void SendChannelModes(TreeServer* Current)
1162         {
1163                 char data[MAXBUF];
1164                 std::deque<std::string> list;
1165                 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
1166                 {
1167                         SendFJoins(Current, c->second);
1168                         snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
1169                         this->WriteLine(data);
1170                         if (*c->second->topic)
1171                         {
1172                                 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);
1173                                 this->WriteLine(data);
1174                         }
1175                         for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
1176                         {
1177                                 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
1178                                 this->WriteLine(data);
1179                         }
1180                         FOREACH_MOD(I_OnSyncChannel,OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this));
1181                         list.clear();
1182                         c->second->GetExtList(list);
1183                         for (unsigned int j = 0; j < list.size(); j++)
1184                         {
1185                                 FOREACH_MOD(I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
1186                         }
1187                 }
1188         }
1189
1190         /* send all users and their oper state/modes */
1191         void SendUsers(TreeServer* Current)
1192         {
1193                 char data[MAXBUF];
1194                 std::deque<std::string> list;
1195                 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
1196                 {
1197                         if (u->second->registered == 7)
1198                         {
1199                                 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);
1200                                 this->WriteLine(data);
1201                                 if (strchr(u->second->modes,'o'))
1202                                 {
1203                                         this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
1204                                 }
1205                                 FOREACH_MOD(I_OnSyncUser,OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this));
1206                                 list.clear();
1207                                 u->second->GetExtList(list);
1208                                 for (unsigned int j = 0; j < list.size(); j++)
1209                                 {
1210                                         FOREACH_MOD(I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
1211                                 }
1212                         }
1213                 }
1214         }
1215
1216         /* This function is called when we want to send a netburst to a local
1217          * server. There is a set order we must do this, because for example
1218          * users require their servers to exist, and channels require their
1219          * users to exist. You get the idea.
1220          */
1221         void DoBurst(TreeServer* s)
1222         {
1223                 Srv->SendOpers("*** Bursting to \2"+s->GetName()+"\2.");
1224                 this->WriteLine("BURST");
1225                 /* send our version string */
1226                 this->WriteLine(":"+Srv->GetServerName()+" VERSION :"+Srv->GetVersion());
1227                 /* Send server tree */
1228                 this->SendServers(TreeRoot,s,1);
1229                 /* Send users and their oper status */
1230                 this->SendUsers(s);
1231                 /* Send everything else (channel modes, xlines etc) */
1232                 this->SendChannelModes(s);
1233                 this->SendXLines(s);
1234                 this->WriteLine("ENDBURST");
1235                 Srv->SendOpers("*** Finished bursting to \2"+s->GetName()+"\2.");
1236         }
1237
1238         /* This function is called when we receive data from a remote
1239          * server. We buffer the data in a std::string (it doesnt stay
1240          * there for long), reading using InspSocket::Read() which can
1241          * read up to 16 kilobytes in one operation.
1242          *
1243          * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
1244          * THE SOCKET OBJECT FOR US.
1245          */
1246         virtual bool OnDataReady()
1247         {
1248                 char* data = this->Read();
1249                 /* Check that the data read is a valid pointer and it has some content */
1250                 if (data && *data)
1251                 {
1252                         this->in_buffer += data;
1253                         /* While there is at least one new line in the buffer,
1254                          * do something useful (we hope!) with it.
1255                          */
1256                         while (in_buffer.find("\n") != std::string::npos)
1257                         {
1258                                 char* line = (char*)in_buffer.c_str();
1259                                 std::string ret = "";
1260                                 while ((*line != '\n') && (strlen(line)))
1261                                 {
1262                                         if ((*line != '\r') && (*line != '\n'))
1263                                                 ret = ret + *line;
1264                                         line++;
1265                                 }
1266                                 if ((*line == '\n') || (*line == '\r'))
1267                                         line++;
1268                                 in_buffer = line;
1269                                 /* Process this one, abort if it
1270                                  * didnt return true.
1271                                  */
1272                                 if (this->ctx_in)
1273                                 {
1274                                         char out[1024];
1275                                         char result[1024];
1276                                         memset(result,0,1024);
1277                                         memset(out,0,1024);
1278                                         log(DEBUG,"Original string '%s'",ret.c_str());
1279                                         /* ERROR + CAPAB is still allowed unencryped */
1280                                         if ((ret.substr(0,7) != "ERROR :") && (ret.substr(0,6) != "CAPAB "))
1281                                         {
1282                                                 int nbytes = from64tobits(out, ret.c_str(), 1024);
1283                                                 if ((nbytes > 0) && (nbytes < 1024))
1284                                                 {
1285                                                         log(DEBUG,"m_spanningtree: decrypt %d bytes",nbytes);
1286                                                         ctx_in->Decrypt(out, result, nbytes, 1);
1287                                                         for (int t = 0; t < nbytes; t++)
1288                                                                 if (result[t] == '\7') result[t] = 0;
1289                                                         ret = result;
1290                                                 }
1291                                         }
1292                                 }
1293                                 if (!this->ProcessLine(ret))
1294                                 {
1295                                         return false;
1296                                 }
1297                         }
1298                 }
1299                 /* EAGAIN returns an empty but non-NULL string, so this
1300                  * evaluates to TRUE for EAGAIN but to FALSE for EOF.
1301                  */
1302                 return (data != NULL);
1303         }
1304
1305         int WriteLine(std::string line)
1306         {
1307                 log(DEBUG,"OUT: %s",line.c_str());
1308                 if (this->ctx_out)
1309                 {
1310                         log(DEBUG,"AES context");
1311                         char result[10240];
1312                         char result64[10240];
1313                         if (this->keylength)
1314                         {
1315                                 while (line.length() % this->keylength != 0)
1316                                 {
1317                                         // pad it to be a multiple of the key length
1318                                         line = line + "\7";
1319                                 }
1320                         }
1321                         unsigned int ll = line.length();
1322                         log(DEBUG,"Plaintext line with padding = %d chars",ll);
1323                         ctx_out->Encrypt(line.c_str(), result, ll, 1);
1324                         log(DEBUG,"Encrypted.");
1325                         to64frombits((unsigned char*)result64,(unsigned char*)result,ll);
1326                         line = result64;
1327                         log(DEBUG,"Encrypted: %s",line.c_str());
1328                         //int from64tobits(char *out, const char *in, int maxlen);
1329                 }
1330                 return this->Write(line + "\r\n");
1331         }
1332
1333         /* Handle ERROR command */
1334         bool Error(std::deque<std::string> params)
1335         {
1336                 if (params.size() < 1)
1337                         return false;
1338                 std::string Errmsg = params[0];
1339                 std::string SName = myhost;
1340                 if (InboundServerName != "")
1341                 {
1342                         SName = InboundServerName;
1343                 }
1344                 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
1345                 /* we will return false to cause the socket to close.
1346                  */
1347                 return false;
1348         }
1349
1350         /* Because the core won't let users or even SERVERS set +o,
1351          * we use the OPERTYPE command to do this.
1352          */
1353         bool OperType(std::string prefix, std::deque<std::string> &params)
1354         {
1355                 if (params.size() != 1)
1356                         return true;
1357                 std::string opertype = params[0];
1358                 userrec* u = Srv->FindNick(prefix);
1359                 if (u)
1360                 {
1361                         strlcpy(u->oper,opertype.c_str(),NICKMAX);
1362                         if (!strchr(u->modes,'o'))
1363                         {
1364                                 strcat(u->modes,"o");
1365                         }
1366                         DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
1367                 }
1368                 return true;
1369         }
1370
1371         /* Because Andy insists that services-compatible servers must
1372          * implement SVSNICK and SVSJOIN, that's exactly what we do :p
1373          */
1374         bool ForceNick(std::string prefix, std::deque<std::string> &params)
1375         {
1376                 if (params.size() < 3)
1377                         return true;
1378                 userrec* u = Srv->FindNick(params[0]);
1379                 if (u)
1380                 {
1381                         Srv->ChangeUserNick(u,params[1]);
1382                         u->age = atoi(params[2].c_str());
1383                         DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
1384                 }
1385                 return true;
1386         }
1387
1388         bool ServiceJoin(std::string prefix, std::deque<std::string> &params)
1389         {
1390                 if (params.size() < 2)
1391                         return true;
1392                 userrec* u = Srv->FindNick(params[0]);
1393                 if (u)
1394                 {
1395                         Srv->JoinUserToChannel(u,params[1],"");
1396                         DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
1397                 }
1398                 return true;
1399         }
1400
1401         bool RemoteRehash(std::string prefix, std::deque<std::string> &params)
1402         {
1403                 if (params.size() < 1)
1404                         return false;
1405                 std::string servermask = params[0];
1406                 if (Srv->MatchText(Srv->GetServerName(),servermask))
1407                 {
1408                         Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
1409                         Srv->RehashServer();
1410                         ReadConfiguration(false);
1411                 }
1412                 DoOneToAllButSender(prefix,"REHASH",params,prefix);
1413                 return true;
1414         }
1415
1416         bool RemoteKill(std::string prefix, std::deque<std::string> &params)
1417         {
1418                 if (params.size() != 2)
1419                         return true;
1420                 std::string nick = params[0];
1421                 userrec* u = Srv->FindNick(prefix);
1422                 userrec* who = Srv->FindNick(nick);
1423                 if (who)
1424                 {
1425                         /* Prepend kill source, if we don't have one */
1426                         std::string sourceserv = prefix;
1427                         if (u)
1428                         {
1429                                 sourceserv = u->server;
1430                         }
1431                         if (*(params[1].c_str()) != '[')
1432                         {
1433                                 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
1434                         }
1435                         std::string reason = params[1];
1436                         params[1] = ":" + params[1];
1437                         DoOneToAllButSender(prefix,"KILL",params,sourceserv);
1438                         Srv->QuitUser(who,reason);
1439                 }
1440                 return true;
1441         }
1442
1443         bool LocalPong(std::string prefix, std::deque<std::string> &params)
1444         {
1445                 if (params.size() < 1)
1446                         return true;
1447                 TreeServer* ServerSource = FindServer(prefix);
1448                 if (ServerSource)
1449                 {
1450                         ServerSource->SetPingFlag();
1451                 }
1452                 return true;
1453         }
1454         
1455         bool MetaData(std::string prefix, std::deque<std::string> &params)
1456         {
1457                 if (params.size() < 3)
1458                         return true;
1459                 TreeServer* ServerSource = FindServer(prefix);
1460                 if (ServerSource)
1461                 {
1462                         if (*(params[0].c_str()) == '#')
1463                         {
1464                                 chanrec* c = Srv->FindChannel(params[0]);
1465                                 if (c)
1466                                 {
1467                                         FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
1468                                 }
1469                         }
1470                         else
1471                         {
1472                                 userrec* u = Srv->FindNick(params[0]);
1473                                 if (u)
1474                                 {
1475                                         FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
1476                                 }
1477                         }
1478                 }
1479                 params[2] = ":" + params[2];
1480                 DoOneToAllButSender(prefix,"METADATA",params,prefix);
1481                 return true;
1482         }
1483
1484         bool ServerVersion(std::string prefix, std::deque<std::string> &params)
1485         {
1486                 if (params.size() < 1)
1487                         return true;
1488                 TreeServer* ServerSource = FindServer(prefix);
1489                 if (ServerSource)
1490                 {
1491                         ServerSource->SetVersion(params[0]);
1492                 }
1493                 params[0] = ":" + params[0];
1494                 DoOneToAllButSender(prefix,"VERSION",params,prefix);
1495                 return true;
1496         }
1497
1498         bool ChangeHost(std::string prefix, std::deque<std::string> &params)
1499         {
1500                 if (params.size() < 1)
1501                         return true;
1502                 userrec* u = Srv->FindNick(prefix);
1503                 if (u)
1504                 {
1505                         Srv->ChangeHost(u,params[0]);
1506                         DoOneToAllButSender(prefix,"FHOST",params,u->server);
1507                 }
1508                 return true;
1509         }
1510
1511         bool AddLine(std::string prefix, std::deque<std::string> &params)
1512         {
1513                 if (params.size() < 6)
1514                         return true;
1515                 std::string linetype = params[0]; /* Z, Q, E, G, K */
1516                 std::string mask = params[1]; /* Line type dependent */
1517                 std::string source = params[2]; /* may not be online or may be a server */
1518                 std::string settime = params[3]; /* EPOCH time set */
1519                 std::string duration = params[4]; /* Duration secs */
1520                 std::string reason = params[5];
1521
1522                 switch (*(linetype.c_str()))
1523                 {
1524                         case 'Z':
1525                                 add_zline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1526                                 zline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1527                         break;
1528                         case 'Q':
1529                                 add_qline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1530                                 qline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1531                         break;
1532                         case 'E':
1533                                 add_eline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1534                                 eline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1535                         break;
1536                         case 'G':
1537                                 add_gline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1538                                 gline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1539                         break;
1540                         case 'K':
1541                                 add_kline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1542                         break;
1543                         default:
1544                                 /* Just in case... */
1545                                 Srv->SendOpers("*** \2WARNING\2: Invalid xline type '"+linetype+"' sent by server "+prefix+", ignored!");
1546                         break;
1547                 }
1548                 /* Send it on its way */
1549                 params[5] = ":" + params[5];
1550                 DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
1551                 return true;
1552         }
1553
1554         bool ChangeName(std::string prefix, std::deque<std::string> &params)
1555         {
1556                 if (params.size() < 1)
1557                         return true;
1558                 userrec* u = Srv->FindNick(prefix);
1559                 if (u)
1560                 {
1561                         Srv->ChangeGECOS(u,params[0]);
1562                         params[0] = ":" + params[0];
1563                         DoOneToAllButSender(prefix,"FNAME",params,u->server);
1564                 }
1565                 return true;
1566         }
1567
1568         bool Whois(std::string prefix, std::deque<std::string> &params)
1569         {
1570                 if (params.size() < 1)
1571                         return true;
1572                 log(DEBUG,"In IDLE command");
1573                 userrec* u = Srv->FindNick(prefix);
1574                 if (u)
1575                 {
1576                         log(DEBUG,"USER EXISTS: %s",u->nick);
1577                         // an incoming request
1578                         if (params.size() == 1)
1579                         {
1580                                 userrec* x = Srv->FindNick(params[0]);
1581                                 if ((x) && (x->fd > -1))
1582                                 {
1583                                         userrec* x = Srv->FindNick(params[0]);
1584                                         log(DEBUG,"Got IDLE");
1585                                         char signon[MAXBUF];
1586                                         char idle[MAXBUF];
1587                                         log(DEBUG,"Sending back IDLE 3");
1588                                         snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
1589                                         snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-time(NULL)));
1590                                         std::deque<std::string> par;
1591                                         par.push_back(prefix);
1592                                         par.push_back(signon);
1593                                         par.push_back(idle);
1594                                         // ours, we're done, pass it BACK
1595                                         DoOneToOne(params[0],"IDLE",par,u->server);
1596                                 }
1597                                 else
1598                                 {
1599                                         // not ours pass it on
1600                                         DoOneToOne(prefix,"IDLE",params,x->server);
1601                                 }
1602                         }
1603                         else if (params.size() == 3)
1604                         {
1605                                 std::string who_did_the_whois = params[0];
1606                                 userrec* who_to_send_to = Srv->FindNick(who_did_the_whois);
1607                                 if ((who_to_send_to) && (who_to_send_to->fd > -1))
1608                                 {
1609                                         log(DEBUG,"Got final IDLE");
1610                                         // an incoming reply to a whois we sent out
1611                                         std::string nick_whoised = prefix;
1612                                         unsigned long signon = atoi(params[1].c_str());
1613                                         unsigned long idle = atoi(params[2].c_str());
1614                                         if ((who_to_send_to) && (who_to_send_to->fd > -1))
1615                                                 do_whois(who_to_send_to,u,signon,idle,(char*)nick_whoised.c_str());
1616                                 }
1617                                 else
1618                                 {
1619                                         // not ours, pass it on
1620                                         DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
1621                                 }
1622                         }
1623                 }
1624                 return true;
1625         }
1626         
1627         bool LocalPing(std::string prefix, std::deque<std::string> &params)
1628         {
1629                 if (params.size() < 1)
1630                         return true;
1631                 std::string stufftobounce = params[0];
1632                 this->WriteLine(":"+Srv->GetServerName()+" PONG "+stufftobounce);
1633                 return true;
1634         }
1635
1636         bool RemoteServer(std::string prefix, std::deque<std::string> &params)
1637         {
1638                 if (params.size() < 4)
1639                         return false;
1640                 std::string servername = params[0];
1641                 std::string password = params[1];
1642                 // hopcount is not used for a remote server, we calculate this ourselves
1643                 std::string description = params[3];
1644                 TreeServer* ParentOfThis = FindServer(prefix);
1645                 if (!ParentOfThis)
1646                 {
1647                         this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
1648                         return false;
1649                 }
1650                 TreeServer* CheckDupe = FindServer(servername);
1651                 if (CheckDupe)
1652                 {
1653                         this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1654                         Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1655                         return false;
1656                 }
1657                 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
1658                 ParentOfThis->AddChild(Node);
1659                 params[3] = ":" + params[3];
1660                 DoOneToAllButSender(prefix,"SERVER",params,prefix);
1661                 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
1662                 return true;
1663         }
1664
1665         bool Outbound_Reply_Server(std::deque<std::string> &params)
1666         {
1667                 if (params.size() < 4)
1668                         return false;
1669                 std::string servername = params[0];
1670                 std::string password = params[1];
1671                 int hops = atoi(params[2].c_str());
1672                 if (hops)
1673                 {
1674                         this->WriteLine("ERROR :Server too far away for authentication");
1675                         Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, server is too far away for authentication");
1676                         return false;
1677                 }
1678                 std::string description = params[3];
1679                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1680                 {
1681                         if ((x->Name == servername) && (x->RecvPass == password))
1682                         {
1683                                 TreeServer* CheckDupe = FindServer(servername);
1684                                 if (CheckDupe)
1685                                 {
1686                                         this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1687                                         Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1688                                         return false;
1689                                 }
1690                                 // Begin the sync here. this kickstarts the
1691                                 // other side, waiting in WAIT_AUTH_2 state,
1692                                 // into starting their burst, as it shows
1693                                 // that we're happy.
1694                                 this->LinkState = CONNECTED;
1695                                 // we should add the details of this server now
1696                                 // to the servers tree, as a child of the root
1697                                 // node.
1698                                 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
1699                                 TreeRoot->AddChild(Node);
1700                                 params[3] = ":" + params[3];
1701                                 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
1702                                 this->bursting = true;
1703                                 this->DoBurst(Node);
1704                                 return true;
1705                         }
1706                 }
1707                 this->WriteLine("ERROR :Invalid credentials");
1708                 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, invalid link credentials");
1709                 return false;
1710         }
1711
1712         bool Inbound_Server(std::deque<std::string> &params)
1713         {
1714                 if (params.size() < 4)
1715                         return false;
1716                 std::string servername = params[0];
1717                 std::string password = params[1];
1718                 int hops = atoi(params[2].c_str());
1719                 if (hops)
1720                 {
1721                         this->WriteLine("ERROR :Server too far away for authentication");
1722                         Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, server is too far away for authentication");
1723                         return false;
1724                 }
1725                 std::string description = params[3];
1726                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1727                 {
1728                         if ((x->Name == servername) && (x->RecvPass == password))
1729                         {
1730                                 TreeServer* CheckDupe = FindServer(servername);
1731                                 if (CheckDupe)
1732                                 {
1733                                         this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1734                                         Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1735                                         return false;
1736                                 }
1737                                 /* If the config says this link is encrypted, but the remote side
1738                                  * hasnt bothered to send the AES command before SERVER, then we
1739                                  * boot them off as we MUST have this connection encrypted.
1740                                  */
1741                                 if ((x->EncryptionKey != "") && (!this->ctx_in))
1742                                 {
1743                                         this->WriteLine("ERROR :This link requires AES encryption to be enabled. Plaintext connection refused.");
1744                                         Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, remote server did not enable AES.");
1745                                         return false;
1746                                 }
1747                                 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
1748                                 this->InboundServerName = servername;
1749                                 this->InboundDescription = description;
1750                                 // this is good. Send our details: Our server name and description and hopcount of 0,
1751                                 // along with the sendpass from this block.
1752                                 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
1753                                 // move to the next state, we are now waiting for THEM.
1754                                 this->LinkState = WAIT_AUTH_2;
1755                                 return true;
1756                         }
1757                 }
1758                 this->WriteLine("ERROR :Invalid credentials");
1759                 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, invalid link credentials");
1760                 return false;
1761         }
1762
1763         void Split(std::string line, bool stripcolon, std::deque<std::string> &n)
1764         {
1765                 if (!strchr(line.c_str(),' '))
1766                 {
1767                         n.push_back(line);
1768                         return;
1769                 }
1770                 std::stringstream s(line);
1771                 std::string param = "";
1772                 n.clear();
1773                 int item = 0;
1774                 while (!s.eof())
1775                 {
1776                         char c;
1777                         s.get(c);
1778                         if (c == ' ')
1779                         {
1780                                 n.push_back(param);
1781                                 param = "";
1782                                 item++;
1783                         }
1784                         else
1785                         {
1786                                 if (!s.eof())
1787                                 {
1788                                         param = param + c;
1789                                 }
1790                                 if ((param == ":") && (item > 0))
1791                                 {
1792                                         param = "";
1793                                         while (!s.eof())
1794                                         {
1795                                                 s.get(c);
1796                                                 if (!s.eof())
1797                                                 {
1798                                                         param = param + c;
1799                                                 }
1800                                         }
1801                                         n.push_back(param);
1802                                         param = "";
1803                                 }
1804                         }
1805                 }
1806                 if (param != "")
1807                 {
1808                         n.push_back(param);
1809                 }
1810                 return;
1811         }
1812
1813         bool ProcessLine(std::string line)
1814         {
1815                 char* l = (char*)line.c_str();
1816                 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
1817                         l[strlen(l)-1] = '\0';
1818                 line = l;
1819                 if (line == "")
1820                         return true;
1821                 Srv->Log(DEBUG,"IN: "+line);
1822                 
1823                 std::deque<std::string> params;
1824                 this->Split(line,true,params);
1825                 std::string command = "";
1826                 std::string prefix = "";
1827                 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
1828                 {
1829                         prefix = params[0];
1830                         command = params[1];
1831                         char* pref = (char*)prefix.c_str();
1832                         prefix = ++pref;
1833                         params.pop_front();
1834                         params.pop_front();
1835                 }
1836                 else
1837                 {
1838                         prefix = "";
1839                         command = params[0];
1840                         params.pop_front();
1841                 }
1842
1843                 if ((!this->ctx_in) && (command == "AES"))
1844                 {
1845                         std::string sserv = params[0];
1846                         for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1847                         {
1848                                 if ((x->EncryptionKey != "") && (x->Name == sserv))
1849                                 {
1850                                         this->InitAES(x->EncryptionKey,sserv);
1851                                 }
1852                         }
1853                         return true;
1854                 }
1855                 else if ((this->ctx_in) && (command == "AES"))
1856                 {
1857                         WriteOpers("*** \2AES\2: Encryption already enabled on this connection yet %s is trying to enable it twice!",params[0].c_str());
1858                 }
1859
1860                 switch (this->LinkState)
1861                 {
1862                         TreeServer* Node;
1863                         
1864                         case WAIT_AUTH_1:
1865                                 // Waiting for SERVER command from remote server. Server initiating
1866                                 // the connection sends the first SERVER command, listening server
1867                                 // replies with theirs if its happy, then if the initiator is happy,
1868                                 // it starts to send its net sync, which starts the merge, otherwise
1869                                 // it sends an ERROR.
1870                                 if (command == "PASS")
1871                                 {
1872                                         /* Silently ignored */
1873                                 }
1874                                 else if (command == "SERVER")
1875                                 {
1876                                         return this->Inbound_Server(params);
1877                                 }
1878                                 else if (command == "ERROR")
1879                                 {
1880                                         return this->Error(params);
1881                                 }
1882                                 else if (command == "USER")
1883                                 {
1884                                         this->WriteLine("ERROR :Client connections to this port are prohibited.");
1885                                         return false;
1886                                 }
1887                                 else if (command == "CAPAB")
1888                                 {
1889                                         return this->Capab(params);
1890                                 }
1891                                 else if ((command == "U") || (command == "S"))
1892                                 {
1893                                         this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
1894                                         return false;
1895                                 }
1896                                 else
1897                                 {
1898                                         this->WriteLine("ERROR :Invalid command in negotiation phase.");
1899                                         return false;
1900                                 }
1901                         break;
1902                         case WAIT_AUTH_2:
1903                                 // Waiting for start of other side's netmerge to say they liked our
1904                                 // password.
1905                                 if (command == "SERVER")
1906                                 {
1907                                         // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1908                                         // silently ignore.
1909                                         return true;
1910                                 }
1911                                 else if ((command == "U") || (command == "S"))
1912                                 {
1913                                         this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
1914                                         return false;
1915                                 }
1916                                 else if (command == "BURST")
1917                                 {
1918                                         this->LinkState = CONNECTED;
1919                                         Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
1920                                         TreeRoot->AddChild(Node);
1921                                         params.clear();
1922                                         params.push_back(InboundServerName);
1923                                         params.push_back("*");
1924                                         params.push_back("1");
1925                                         params.push_back(":"+InboundDescription);
1926                                         DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
1927                                         this->bursting = true;
1928                                         this->DoBurst(Node);
1929                                 }
1930                                 else if (command == "ERROR")
1931                                 {
1932                                         return this->Error(params);
1933                                 }
1934                                 else if (command == "CAPAB")
1935                                 {
1936                                         return this->Capab(params);
1937                                 }
1938                                 
1939                         break;
1940                         case LISTENER:
1941                                 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
1942                                 return false;
1943                         break;
1944                         case CONNECTING:
1945                                 if (command == "SERVER")
1946                                 {
1947                                         // another server we connected to, which was in WAIT_AUTH_1 state,
1948                                         // has just sent us their credentials. If we get this far, theyre
1949                                         // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1950                                         // if we're happy with this, we should send our netburst which
1951                                         // kickstarts the merge.
1952                                         return this->Outbound_Reply_Server(params);
1953                                 }
1954                                 else if (command == "ERROR")
1955                                 {
1956                                         return this->Error(params);
1957                                 }
1958                         break;
1959                         case CONNECTED:
1960                                 // This is the 'authenticated' state, when all passwords
1961                                 // have been exchanged and anything past this point is taken
1962                                 // as gospel.
1963                                 
1964                                 if (prefix != "")
1965                                 {
1966                                         std::string direction = prefix;
1967                                         userrec* t = Srv->FindNick(prefix);
1968                                         if (t)
1969                                         {
1970                                                 direction = t->server;
1971                                         }
1972                                         TreeServer* route_back_again = BestRouteTo(direction);
1973                                         if ((!route_back_again) || (route_back_again->GetSocket() != this))
1974                                         {
1975                                                 if (route_back_again)
1976                                                         log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
1977                                                 return true;
1978                                         }
1979
1980                                         /* Fix by brain:
1981                                          * When there is activity on the socket, reset the ping counter so
1982                                          * that we're not wasting bandwidth pinging an active server.
1983                                          */                     
1984                                         route_back_again->SetNextPingTime(time(NULL) + 120);
1985                                         route_back_again->SetPingFlag();
1986                                 }
1987                                 
1988                                 if (command == "SVSMODE")
1989                                 {
1990                                         /* Services expects us to implement
1991                                          * SVSMODE. In inspircd its the same as
1992                                          * MODE anyway.
1993                                          */
1994                                         command = "MODE";
1995                                 }
1996                                 std::string target = "";
1997                                 /* Yes, know, this is a mess. Its reasonably fast though as we're
1998                                  * working with std::string here.
1999                                  */
2000                                 if ((command == "NICK") && (params.size() > 1))
2001                                 {
2002                                         return this->IntroduceClient(prefix,params);
2003                                 }
2004                                 else if (command == "FJOIN")
2005                                 {
2006                                         return this->ForceJoin(prefix,params);
2007                                 }
2008                                 else if (command == "SERVER")
2009                                 {
2010                                         return this->RemoteServer(prefix,params);
2011                                 }
2012                                 else if (command == "ERROR")
2013                                 {
2014                                         return this->Error(params);
2015                                 }
2016                                 else if (command == "OPERTYPE")
2017                                 {
2018                                         return this->OperType(prefix,params);
2019                                 }
2020                                 else if (command == "FMODE")
2021                                 {
2022                                         return this->ForceMode(prefix,params);
2023                                 }
2024                                 else if (command == "KILL")
2025                                 {
2026                                         return this->RemoteKill(prefix,params);
2027                                 }
2028                                 else if (command == "FTOPIC")
2029                                 {
2030                                         return this->ForceTopic(prefix,params);
2031                                 }
2032                                 else if (command == "REHASH")
2033                                 {
2034                                         return this->RemoteRehash(prefix,params);
2035                                 }
2036                                 else if (command == "METADATA")
2037                                 {
2038                                         return this->MetaData(prefix,params);
2039                                 }
2040                                 else if (command == "PING")
2041                                 {
2042                                         return this->LocalPing(prefix,params);
2043                                 }
2044                                 else if (command == "PONG")
2045                                 {
2046                                         return this->LocalPong(prefix,params);
2047                                 }
2048                                 else if (command == "VERSION")
2049                                 {
2050                                         return this->ServerVersion(prefix,params);
2051                                 }
2052                                 else if (command == "FHOST")
2053                                 {
2054                                         return this->ChangeHost(prefix,params);
2055                                 }
2056                                 else if (command == "FNAME")
2057                                 {
2058                                         return this->ChangeName(prefix,params);
2059                                 }
2060                                 else if (command == "ADDLINE")
2061                                 {
2062                                         return this->AddLine(prefix,params);
2063                                 }
2064                                 else if (command == "SVSNICK")
2065                                 {
2066                                         if (prefix == "")
2067                                         {
2068                                                 prefix = this->GetName();
2069                                         }
2070                                         return this->ForceNick(prefix,params);
2071                                 }
2072                                 else if (command == "IDLE")
2073                                 {
2074                                         return this->Whois(prefix,params);
2075                                 }
2076                                 else if (command == "SVSJOIN")
2077                                 {
2078                                         if (prefix == "")
2079                                         {
2080                                                 prefix = this->GetName();
2081                                         }
2082                                         return this->ServiceJoin(prefix,params);
2083                                 }
2084                                 else if (command == "SQUIT")
2085                                 {
2086                                         if (params.size() == 2)
2087                                         {
2088                                                 this->Squit(FindServer(params[0]),params[1]);
2089                                         }
2090                                         return true;
2091                                 }
2092                                 else if (command == "ENDBURST")
2093                                 {
2094                                         this->bursting = false;
2095                                         return true;
2096                                 }
2097                                 else
2098                                 {
2099                                         // not a special inter-server command.
2100                                         // Emulate the actual user doing the command,
2101                                         // this saves us having a huge ugly parser.
2102                                         userrec* who = Srv->FindNick(prefix);
2103                                         std::string sourceserv = this->myhost;
2104                                         if (this->InboundServerName != "")
2105                                         {
2106                                                 sourceserv = this->InboundServerName;
2107                                         }
2108                                         if (who)
2109                                         {
2110                                                 // its a user
2111                                                 target = who->server;
2112                                                 char* strparams[127];
2113                                                 for (unsigned int q = 0; q < params.size(); q++)
2114                                                 {
2115                                                         strparams[q] = (char*)params[q].c_str();
2116                                                 }
2117                                                 Srv->CallCommandHandler(command, strparams, params.size(), who);
2118                                         }
2119                                         else
2120                                         {
2121                                                 // its not a user. Its either a server, or somethings screwed up.
2122                                                 if (IsServer(prefix))
2123                                                 {
2124                                                         target = Srv->GetServerName();
2125                                                 }
2126                                                 else
2127                                                 {
2128                                                         log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
2129                                                         return true;
2130                                                 }
2131                                         }
2132                                         return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
2133
2134                                 }
2135                                 return true;
2136                         break;
2137                 }
2138                 return true;
2139         }
2140
2141         virtual std::string GetName()
2142         {
2143                 std::string sourceserv = this->myhost;
2144                 if (this->InboundServerName != "")
2145                 {
2146                         sourceserv = this->InboundServerName;
2147                 }
2148                 return sourceserv;
2149         }
2150
2151         virtual void OnTimeout()
2152         {
2153                 if (this->LinkState == CONNECTING)
2154                 {
2155                         Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
2156                 }
2157         }
2158
2159         virtual void OnClose()
2160         {
2161                 // Connection closed.
2162                 // If the connection is fully up (state CONNECTED)
2163                 // then propogate a netsplit to all peers.
2164                 std::string quitserver = this->myhost;
2165                 if (this->InboundServerName != "")
2166                 {
2167                         quitserver = this->InboundServerName;
2168                 }
2169                 TreeServer* s = FindServer(quitserver);
2170                 if (s)
2171                 {
2172                         Squit(s,"Remote host closed the connection");
2173                 }
2174                 WriteOpers("Server '\2%s\2[%s]' closed the connection.",quitserver.c_str(),this->GetIP().c_str());
2175         }
2176
2177         virtual int OnIncomingConnection(int newsock, char* ip)
2178         {
2179                 TreeSocket* s = new TreeSocket(newsock, ip);
2180                 Srv->AddSocket(s);
2181                 return true;
2182         }
2183 };
2184
2185 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
2186 {
2187         for (unsigned int c = 0; c < list.size(); c++)
2188         {
2189                 if (list[c] == server)
2190                 {
2191                         return;
2192                 }
2193         }
2194         list.push_back(server);
2195 }
2196
2197 // returns a list of DIRECT servernames for a specific channel
2198 void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
2199 {
2200         std::map<char*,char*> *ulist = c->GetUsers();
2201         for (std::map<char*,char*>::iterator i = ulist->begin(); i != ulist->end(); i++)
2202         {
2203                 char* o = i->second;
2204                 userrec* otheruser = (userrec*)o;
2205                 if (otheruser->fd < 0)
2206                 {
2207                         TreeServer* best = BestRouteTo(otheruser->server);
2208                         if (best)
2209                                 AddThisServer(best,list);
2210                 }
2211         }
2212         return;
2213 }
2214
2215 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, std::string command, std::deque<std::string> &params)
2216 {
2217         TreeServer* omitroute = BestRouteTo(omit);
2218         if ((command == "NOTICE") || (command == "PRIVMSG"))
2219         {
2220                 if ((params.size() >= 2) && (*(params[0].c_str()) != '$'))
2221                 {
2222                         if (*(params[0].c_str()) != '#')
2223                         {
2224                                 // special routing for private messages/notices
2225                                 userrec* d = Srv->FindNick(params[0]);
2226                                 if (d)
2227                                 {
2228                                         std::deque<std::string> par;
2229                                         par.push_back(params[0]);
2230                                         par.push_back(":"+params[1]);
2231                                         DoOneToOne(prefix,command,par,d->server);
2232                                         return true;
2233                                 }
2234                         }
2235                         else
2236                         {
2237                                 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
2238                                 chanrec* c = Srv->FindChannel(params[0]);
2239                                 if (c)
2240                                 {
2241                                         std::deque<TreeServer*> list;
2242                                         GetListOfServersForChannel(c,list);
2243                                         log(DEBUG,"Got a list of %d servers",list.size());
2244                                         unsigned int lsize = list.size();
2245                                         for (unsigned int i = 0; i < lsize; i++)
2246                                         {
2247                                                 TreeSocket* Sock = list[i]->GetSocket();
2248                                                 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
2249                                                 {
2250                                                         log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
2251                                                         Sock->WriteLine(data);
2252                                                 }
2253                                         }
2254                                         return true;
2255                                 }
2256                         }
2257                 }
2258         }
2259         unsigned int items = TreeRoot->ChildCount();
2260         for (unsigned int x = 0; x < items; x++)
2261         {
2262                 TreeServer* Route = TreeRoot->GetChild(x);
2263                 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
2264                 {
2265                         TreeSocket* Sock = Route->GetSocket();
2266                         Sock->WriteLine(data);
2267                 }
2268         }
2269         return true;
2270 }
2271
2272 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> &params, std::string omit)
2273 {
2274         TreeServer* omitroute = BestRouteTo(omit);
2275         std::string FullLine = ":" + prefix + " " + command;
2276         unsigned int words = params.size();
2277         for (unsigned int x = 0; x < words; x++)
2278         {
2279                 FullLine = FullLine + " " + params[x];
2280         }
2281         unsigned int items = TreeRoot->ChildCount();
2282         for (unsigned int x = 0; x < items; x++)
2283         {
2284                 TreeServer* Route = TreeRoot->GetChild(x);
2285                 // Send the line IF:
2286                 // The route has a socket (its a direct connection)
2287                 // The route isnt the one to be omitted
2288                 // The route isnt the path to the one to be omitted
2289                 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
2290                 {
2291                         TreeSocket* Sock = Route->GetSocket();
2292                         Sock->WriteLine(FullLine);
2293                 }
2294         }
2295         return true;
2296 }
2297
2298 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> &params)
2299 {
2300         std::string FullLine = ":" + prefix + " " + command;
2301         unsigned int words = params.size();
2302         for (unsigned int x = 0; x < words; x++)
2303         {
2304                 FullLine = FullLine + " " + params[x];
2305         }
2306         unsigned int items = TreeRoot->ChildCount();
2307         for (unsigned int x = 0; x < items; x++)
2308         {
2309                 TreeServer* Route = TreeRoot->GetChild(x);
2310                 if (Route->GetSocket())
2311                 {
2312                         TreeSocket* Sock = Route->GetSocket();
2313                         Sock->WriteLine(FullLine);
2314                 }
2315         }
2316         return true;
2317 }
2318
2319 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> &params, std::string target)
2320 {
2321         TreeServer* Route = BestRouteTo(target);
2322         if (Route)
2323         {
2324                 std::string FullLine = ":" + prefix + " " + command;
2325                 unsigned int words = params.size();
2326                 for (unsigned int x = 0; x < words; x++)
2327                 {
2328                         FullLine = FullLine + " " + params[x];
2329                 }
2330                 if (Route->GetSocket())
2331                 {
2332                         TreeSocket* Sock = Route->GetSocket();
2333                         Sock->WriteLine(FullLine);
2334                 }
2335                 return true;
2336         }
2337         else
2338         {
2339                 return true;
2340         }
2341 }
2342
2343 std::vector<TreeSocket*> Bindings;
2344
2345 void ReadConfiguration(bool rebind)
2346 {
2347         Conf = new ConfigReader;
2348         if (rebind)
2349         {
2350                 for (int j =0; j < Conf->Enumerate("bind"); j++)
2351                 {
2352                         std::string Type = Conf->ReadValue("bind","type",j);
2353                         std::string IP = Conf->ReadValue("bind","address",j);
2354                         long Port = Conf->ReadInteger("bind","port",j,true);
2355                         if (Type == "servers")
2356                         {
2357                                 if (IP == "*")
2358                                 {
2359                                         IP = "";
2360                                 }
2361                                 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
2362                                 if (listener->GetState() == I_LISTENING)
2363                                 {
2364                                         Srv->AddSocket(listener);
2365                                         Bindings.push_back(listener);
2366                                 }
2367                                 else
2368                                 {
2369                                         log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
2370                                         listener->Close();
2371                                         delete listener;
2372                                 }
2373                         }
2374                 }
2375         }
2376         LinkBlocks.clear();
2377         for (int j =0; j < Conf->Enumerate("link"); j++)
2378         {
2379                 Link L;
2380                 L.Name = Conf->ReadValue("link","name",j);
2381                 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
2382                 L.Port = Conf->ReadInteger("link","port",j,true);
2383                 L.SendPass = Conf->ReadValue("link","sendpass",j);
2384                 L.RecvPass = Conf->ReadValue("link","recvpass",j);
2385                 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
2386                 L.EncryptionKey =  Conf->ReadValue("link","encryptionkey",j);
2387                 L.NextConnectTime = time(NULL) + L.AutoConnect;
2388                 /* Bugfix by brain, do not allow people to enter bad configurations */
2389                 if ((L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
2390                 {
2391                         LinkBlocks.push_back(L);
2392                         log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
2393                 }
2394                 else
2395                 {
2396                         if (L.RecvPass == "")
2397                         {
2398                                 log(DEFAULT,"Invalid configuration for server '%s', recvpass not defined!",L.Name.c_str());
2399                         }
2400                         else if (L.SendPass == "")
2401                         {
2402                                 log(DEFAULT,"Invalid configuration for server '%s', sendpass not defined!",L.Name.c_str());
2403                         }
2404                         else if (L.Name == "")
2405                         {
2406                                 log(DEFAULT,"Invalid configuration, link tag without a name!");
2407                         }
2408                         else if (!L.Port)
2409                         {
2410                                 log(DEFAULT,"Invalid configuration for server '%s', no port specified!",L.Name.c_str());
2411                         }
2412                 }
2413         }
2414         delete Conf;
2415 }
2416
2417
2418 class ModuleSpanningTree : public Module
2419 {
2420         std::vector<TreeSocket*> Bindings;
2421         int line;
2422         int NumServers;
2423
2424  public:
2425
2426         ModuleSpanningTree(Server* Me)
2427                 : Module::Module(Me)
2428         {
2429                 Srv = Me;
2430                 Bindings.clear();
2431
2432                 // Create the root of the tree
2433                 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
2434
2435                 ReadConfiguration(true);
2436         }
2437
2438         void ShowLinks(TreeServer* Current, userrec* user, int hops)
2439         {
2440                 std::string Parent = TreeRoot->GetName();
2441                 if (Current->GetParent())
2442                 {
2443                         Parent = Current->GetParent()->GetName();
2444                 }
2445                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
2446                 {
2447                         ShowLinks(Current->GetChild(q),user,hops+1);
2448                 }
2449                 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
2450         }
2451
2452         int CountLocalServs()
2453         {
2454                 return TreeRoot->ChildCount();
2455         }
2456
2457         int CountServs()
2458         {
2459                 return serverlist.size();
2460         }
2461
2462         void HandleLinks(char** parameters, int pcnt, userrec* user)
2463         {
2464                 ShowLinks(TreeRoot,user,0);
2465                 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
2466                 return;
2467         }
2468
2469         void HandleLusers(char** parameters, int pcnt, userrec* user)
2470         {
2471                 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),this->CountServs());
2472                 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
2473                 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
2474                 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
2475                 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
2476                 return;
2477         }
2478
2479         // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
2480
2481         void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
2482         {
2483                 if (line < 128)
2484                 {
2485                         for (int t = 0; t < depth; t++)
2486                         {
2487                                 matrix[line][t] = ' ';
2488                         }
2489
2490                         // For Aligning, we need to work out exactly how deep this thing is, and produce
2491                         // a 'Spacer' String to compensate.
2492                         char spacer[40];
2493
2494                         memset(spacer,' ',40);
2495                         if ((40 - Current->GetName().length() - depth) > 1) {
2496                                 spacer[40 - Current->GetName().length() - depth] = '\0';
2497                         }
2498                         else
2499                         {
2500                                 spacer[5] = '\0';
2501                         }
2502
2503                         float percent;
2504                         char text[80];
2505                         if (clientlist.size() == 0) {
2506                                 // If there are no users, WHO THE HELL DID THE /MAP?!?!?!
2507                                 percent = 0;
2508                         }
2509                         else
2510                         {
2511                                 percent = ((float)Current->GetUserCount() / (float)clientlist.size()) * 100;
2512                         }
2513                         snprintf(text, 80, "%s %s%5d [%5.2f%%]", Current->GetName().c_str(), spacer, Current->GetUserCount(), percent);
2514                         strlcpy(&matrix[line][depth],text,80);
2515                         line++;
2516                         for (unsigned int q = 0; q < Current->ChildCount(); q++)
2517                         {
2518                                 ShowMap(Current->GetChild(q),user,depth+2,matrix);
2519                         }
2520                 }
2521         }
2522
2523         // Ok, prepare to be confused.
2524         // After much mulling over how to approach this, it struck me that
2525         // the 'usual' way of doing a /MAP isnt the best way. Instead of
2526         // keeping track of a ton of ascii characters, and line by line
2527         // under recursion working out where to place them using multiplications
2528         // and divisons, we instead render the map onto a backplane of characters
2529         // (a character matrix), then draw the branches as a series of "L" shapes
2530         // from the nodes. This is not only friendlier on CPU it uses less stack.
2531
2532         void HandleMap(char** parameters, int pcnt, userrec* user)
2533         {
2534                 // This array represents a virtual screen which we will
2535                 // "scratch" draw to, as the console device of an irc
2536                 // client does not provide for a proper terminal.
2537                 char matrix[128][80];
2538                 for (unsigned int t = 0; t < 128; t++)
2539                 {
2540                         matrix[t][0] = '\0';
2541                 }
2542                 line = 0;
2543                 // The only recursive bit is called here.
2544                 ShowMap(TreeRoot,user,0,matrix);
2545                 // Process each line one by one. The algorithm has a limit of
2546                 // 128 servers (which is far more than a spanning tree should have
2547                 // anyway, so we're ok). This limit can be raised simply by making
2548                 // the character matrix deeper, 128 rows taking 10k of memory.
2549                 for (int l = 1; l < line; l++)
2550                 {
2551                         // scan across the line looking for the start of the
2552                         // servername (the recursive part of the algorithm has placed
2553                         // the servers at indented positions depending on what they
2554                         // are related to)
2555                         int first_nonspace = 0;
2556                         while (matrix[l][first_nonspace] == ' ')
2557                         {
2558                                 first_nonspace++;
2559                         }
2560                         first_nonspace--;
2561                         // Draw the `- (corner) section: this may be overwritten by
2562                         // another L shape passing along the same vertical pane, becoming
2563                         // a |- (branch) section instead.
2564                         matrix[l][first_nonspace] = '-';
2565                         matrix[l][first_nonspace-1] = '`';
2566                         int l2 = l - 1;
2567                         // Draw upwards until we hit the parent server, causing possibly
2568                         // other corners (`-) to become branches (|-)
2569                         while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
2570                         {
2571                                 matrix[l2][first_nonspace-1] = '|';
2572                                 l2--;
2573                         }
2574                 }
2575                 // dump the whole lot to the user. This is the easy bit, honest.
2576                 for (int t = 0; t < line; t++)
2577                 {
2578                         WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
2579                 }
2580                 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
2581                 return;
2582         }
2583
2584         int HandleSquit(char** parameters, int pcnt, userrec* user)
2585         {
2586                 TreeServer* s = FindServerMask(parameters[0]);
2587                 if (s)
2588                 {
2589                         if (s == TreeRoot)
2590                         {
2591                                  WriteServ(user->fd,"NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
2592                                 return 1;
2593                         }
2594                         TreeSocket* sock = s->GetSocket();
2595                         if (sock)
2596                         {
2597                                 log(DEBUG,"Splitting server %s",s->GetName().c_str());
2598                                 WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
2599                                 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
2600                                 Srv->RemoveSocket(sock);
2601                         }
2602                         else
2603                         {
2604                                 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
2605                         }
2606                 }
2607                 else
2608                 {
2609                          WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
2610                 }
2611                 return 1;
2612         }
2613
2614         int HandleRemoteWhois(char** parameters, int pcnt, userrec* user)
2615         {
2616                 if ((user->fd > -1) && (pcnt > 1))
2617                 {
2618                         userrec* remote = Srv->FindNick(parameters[1]);
2619                         if ((remote) && (remote->fd < 0))
2620                         {
2621                                 std::deque<std::string> params;
2622                                 params.push_back(parameters[1]);
2623                                 DoOneToOne(user->nick,"IDLE",params,remote->server);
2624                                 return 1;
2625                         }
2626                         else if (!remote)
2627                         {
2628                                 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
2629                                 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
2630                                 return 1;
2631                         }
2632                 }
2633                 return 0;
2634         }
2635
2636         void DoPingChecks(time_t curtime)
2637         {
2638                 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
2639                 {
2640                         TreeServer* serv = TreeRoot->GetChild(j);
2641                         TreeSocket* sock = serv->GetSocket();
2642                         if (sock)
2643                         {
2644                                 if (curtime >= serv->NextPingTime())
2645                                 {               
2646                                         if (serv->AnsweredLastPing())
2647                                         {               
2648                                                 sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
2649                                                 serv->SetNextPingTime(curtime + 120);
2650                                         }                       
2651                                         else            
2652                                         {       
2653                                                 // they didnt answer, boot them
2654                                                 WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
2655                                                 sock->Squit(serv,"Ping timeout");
2656                                                 Srv->RemoveSocket(sock);
2657                                                 return;
2658                                         }
2659                                 }
2660
2661                         }
2662                 }
2663         }
2664
2665         void AutoConnectServers(time_t curtime)
2666         {
2667                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2668                 {
2669                         if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
2670                         {
2671                                 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
2672                                 x->NextConnectTime = curtime + x->AutoConnect;
2673                                 TreeServer* CheckDupe = FindServer(x->Name);
2674                                 if (!CheckDupe)
2675                                 {
2676                                         // an autoconnected server is not connected. Check if its time to connect it
2677                                         WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
2678                                         TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2679                                         Srv->AddSocket(newsocket);
2680                                 }
2681                         }
2682                 }
2683         }
2684
2685         int HandleVersion(char** parameters, int pcnt, userrec* user)
2686         {
2687                 // we've already checked if pcnt > 0, so this is safe
2688                 TreeServer* found = FindServerMask(parameters[0]);
2689                 if (found)
2690                 {
2691                         std::string Version = found->GetVersion();
2692                         WriteServ(user->fd,"351 %s :%s",user->nick,Version.c_str());
2693                         if (found == TreeRoot)
2694                         {
2695                                 std::stringstream out(Config->data005);
2696                                 std::string token = "";
2697                                 std::string line5 = "";
2698                                 int token_counter = 0;
2699                                 while (!out.eof())
2700                                 {
2701                                         out >> token;
2702                                         line5 = line5 + token + " ";   
2703                                         token_counter++;
2704                                         if ((token_counter >= 13) || (out.eof() == true))
2705                                         {
2706                                                 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
2707                                                 line5 = "";
2708                                                 token_counter = 0;
2709                                         }
2710                                 }
2711                         }
2712                 }
2713                 else
2714                 {
2715                         WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
2716                 }
2717                 return 1;
2718         }
2719         
2720         int HandleConnect(char** parameters, int pcnt, userrec* user)
2721         {
2722                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2723                 {
2724                         if (Srv->MatchText(x->Name.c_str(),parameters[0]))
2725                         {
2726                                 TreeServer* CheckDupe = FindServer(x->Name);
2727                                 if (!CheckDupe)
2728                                 {
2729                                         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);
2730                                         TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2731                                         Srv->AddSocket(newsocket);
2732                                         return 1;
2733                                 }
2734                                 else
2735                                 {
2736                                         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());
2737                                         return 1;
2738                                 }
2739                         }
2740                 }
2741                 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
2742                 return 1;
2743         }
2744
2745         virtual int OnStats(char statschar, userrec* user)
2746         {
2747                 if (statschar == 'c')
2748                 {
2749                         for (unsigned int i = 0; i < LinkBlocks.size(); i++)
2750                         {
2751                                 WriteServ(user->fd,"213 %s C *@%s * %s %d 0 %c%c%c",user->nick,LinkBlocks[i].IPAddr.c_str(),LinkBlocks[i].Name.c_str(),LinkBlocks[i].Port,(LinkBlocks[i].EncryptionKey != "" ? 'e' : '-'),(LinkBlocks[i].AutoConnect ? 'a' : '-'),'s');
2752                                 WriteServ(user->fd,"244 %s H * * %s",user->nick,LinkBlocks[i].Name.c_str());
2753                         }
2754                         WriteServ(user->fd,"219 %s %c :End of /STATS report",user->nick,statschar);
2755                         WriteOpers("*** Notice: Stats '%c' requested by %s (%s@%s)",statschar,user->nick,user->ident,user->host);
2756                         return 1;
2757                 }
2758                 return 0;
2759         }
2760
2761         virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user, bool validated)
2762         {
2763                 /* If the command doesnt appear to be valid, we dont want to mess with it. */
2764                 if (!validated)
2765                         return 0;
2766
2767                 if (command == "CONNECT")
2768                 {
2769                         return this->HandleConnect(parameters,pcnt,user);
2770                 }
2771                 else if (command == "SQUIT")
2772                 {
2773                         return this->HandleSquit(parameters,pcnt,user);
2774                 }
2775                 else if (command == "MAP")
2776                 {
2777                         this->HandleMap(parameters,pcnt,user);
2778                         return 1;
2779                 }
2780                 else if (command == "LUSERS")
2781                 {
2782                         this->HandleLusers(parameters,pcnt,user);
2783                         return 1;
2784                 }
2785                 else if (command == "LINKS")
2786                 {
2787                         this->HandleLinks(parameters,pcnt,user);
2788                         return 1;
2789                 }
2790                 else if (command == "WHOIS")
2791                 {
2792                         if (pcnt > 1)
2793                         {
2794                                 // remote whois
2795                                 return this->HandleRemoteWhois(parameters,pcnt,user);
2796                         }
2797                 }
2798                 else if ((command == "VERSION") && (pcnt > 0))
2799                 {
2800                         this->HandleVersion(parameters,pcnt,user);
2801                         return 1;
2802                 }
2803                 else if (Srv->IsValidModuleCommand(command, pcnt, user))
2804                 {
2805                         // this bit of code cleverly routes all module commands
2806                         // to all remote severs *automatically* so that modules
2807                         // can just handle commands locally, without having
2808                         // to have any special provision in place for remote
2809                         // commands and linking protocols.
2810                         std::deque<std::string> params;
2811                         params.clear();
2812                         for (int j = 0; j < pcnt; j++)
2813                         {
2814                                 if (strchr(parameters[j],' '))
2815                                 {
2816                                         params.push_back(":" + std::string(parameters[j]));
2817                                 }
2818                                 else
2819                                 {
2820                                         params.push_back(std::string(parameters[j]));
2821                                 }
2822                         }
2823                         DoOneToMany(user->nick,command,params);
2824                 }
2825                 return 0;
2826         }
2827
2828         virtual void OnGetServerDescription(std::string servername,std::string &description)
2829         {
2830                 TreeServer* s = FindServer(servername);
2831                 if (s)
2832                 {
2833                         description = s->GetDesc();
2834                 }
2835         }
2836
2837         virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
2838         {
2839                 if (source->fd > -1)
2840                 {
2841                         std::deque<std::string> params;
2842                         params.push_back(dest->nick);
2843                         params.push_back(channel->name);
2844                         DoOneToMany(source->nick,"INVITE",params);
2845                 }
2846         }
2847
2848         virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
2849         {
2850                 std::deque<std::string> params;
2851                 params.push_back(chan->name);
2852                 params.push_back(":"+topic);
2853                 DoOneToMany(user->nick,"TOPIC",params);
2854         }
2855
2856         virtual void OnWallops(userrec* user, std::string text)
2857         {
2858                 if (user->fd > -1)
2859                 {
2860                         std::deque<std::string> params;
2861                         params.push_back(":"+text);
2862                         DoOneToMany(user->nick,"WALLOPS",params);
2863                 }
2864         }
2865
2866         virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
2867         {
2868                 if (target_type == TYPE_USER)
2869                 {
2870                         userrec* d = (userrec*)dest;
2871                         if ((d->fd < 0) && (user->fd > -1))
2872                         {
2873                                 std::deque<std::string> params;
2874                                 params.clear();
2875                                 params.push_back(d->nick);
2876                                 params.push_back(":"+text);
2877                                 DoOneToOne(user->nick,"NOTICE",params,d->server);
2878                         }
2879                 }
2880                 else
2881                 {
2882                         if (user->fd > -1)
2883                         {
2884                                 chanrec *c = (chanrec*)dest;
2885                                 std::deque<TreeServer*> list;
2886                                 GetListOfServersForChannel(c,list);
2887                                 unsigned int ucount = list.size();
2888                                 for (unsigned int i = 0; i < ucount; i++)
2889                                 {
2890                                         TreeSocket* Sock = list[i]->GetSocket();
2891                                         if (Sock)
2892                                                 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+std::string(c->name)+" :"+text);
2893                                 }
2894                         }
2895                 }
2896         }
2897
2898         virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
2899         {
2900                 if (target_type == TYPE_USER)
2901                 {
2902                         // route private messages which are targetted at clients only to the server
2903                         // which needs to receive them
2904                         userrec* d = (userrec*)dest;
2905                         if ((d->fd < 0) && (user->fd > -1))
2906                         {
2907                                 std::deque<std::string> params;
2908                                 params.clear();
2909                                 params.push_back(d->nick);
2910                                 params.push_back(":"+text);
2911                                 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
2912                         }
2913                 }
2914                 else
2915                 {
2916                         if (user->fd > -1)
2917                         {
2918                                 chanrec *c = (chanrec*)dest;
2919                                 std::deque<TreeServer*> list;
2920                                 GetListOfServersForChannel(c,list);
2921                                 unsigned int ucount = list.size();
2922                                 for (unsigned int i = 0; i < ucount; i++)
2923                                 {
2924                                         TreeSocket* Sock = list[i]->GetSocket();
2925                                         if (Sock)
2926                                                 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+std::string(c->name)+" :"+text);
2927                                 }
2928                         }
2929                 }
2930         }
2931
2932         virtual void OnBackgroundTimer(time_t curtime)
2933         {
2934                 AutoConnectServers(curtime);
2935                 DoPingChecks(curtime);
2936         }
2937
2938         virtual void OnUserJoin(userrec* user, chanrec* channel)
2939         {
2940                 // Only do this for local users
2941                 if (user->fd > -1)
2942                 {
2943                         std::deque<std::string> params;
2944                         params.clear();
2945                         params.push_back(channel->name);
2946                         if (*channel->key)
2947                         {
2948                                 // if the channel has a key, force the join by emulating the key.
2949                                 params.push_back(channel->key);
2950                         }
2951                         if (channel->GetUserCounter() > 1)
2952                         {
2953                                 // not the first in the channel
2954                                 DoOneToMany(user->nick,"JOIN",params);
2955                         }
2956                         else
2957                         {
2958                                 // first in the channel, set up their permissions
2959                                 // and the channel TS with FJOIN.
2960                                 char ts[24];
2961                                 snprintf(ts,24,"%lu",(unsigned long)channel->age);
2962                                 params.clear();
2963                                 params.push_back(channel->name);
2964                                 params.push_back(ts);
2965                                 params.push_back("@"+std::string(user->nick));
2966                                 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
2967                         }
2968                 }
2969         }
2970
2971         virtual void OnChangeHost(userrec* user, std::string newhost)
2972         {
2973                 // only occurs for local clients
2974                 if (user->registered != 7)
2975                         return;
2976                 std::deque<std::string> params;
2977                 params.push_back(newhost);
2978                 DoOneToMany(user->nick,"FHOST",params);
2979         }
2980
2981         virtual void OnChangeName(userrec* user, std::string gecos)
2982         {
2983                 // only occurs for local clients
2984                 if (user->registered != 7)
2985                         return;
2986                 std::deque<std::string> params;
2987                 params.push_back(gecos);
2988                 DoOneToMany(user->nick,"FNAME",params);
2989         }
2990
2991         virtual void OnUserPart(userrec* user, chanrec* channel, std::string partmessage)
2992         {
2993                 if (user->fd > -1)
2994                 {
2995                         std::deque<std::string> params;
2996                         params.push_back(channel->name);
2997                         if (partmessage != "")
2998                                 params.push_back(":"+partmessage);
2999                         DoOneToMany(user->nick,"PART",params);
3000                 }
3001         }
3002
3003         virtual void OnUserConnect(userrec* user)
3004         {
3005                 char agestr[MAXBUF];
3006                 if (user->fd > -1)
3007                 {
3008                         std::deque<std::string> params;
3009                         snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
3010                         params.push_back(agestr);
3011                         params.push_back(user->nick);
3012                         params.push_back(user->host);
3013                         params.push_back(user->dhost);
3014                         params.push_back(user->ident);
3015                         params.push_back("+"+std::string(user->modes));
3016                         params.push_back(user->ip);
3017                         params.push_back(":"+std::string(user->fullname));
3018                         DoOneToMany(Srv->GetServerName(),"NICK",params);
3019
3020                         // User is Local, change needs to be reflected!
3021                         TreeServer* SourceServer = FindServer(user->server);
3022                         if (SourceServer) {
3023                                 SourceServer->AddUserCount();
3024                         }
3025
3026                 }
3027         }
3028
3029         virtual void OnUserQuit(userrec* user, std::string reason)
3030         {
3031                 if ((user->fd > -1) && (user->registered == 7))
3032                 {
3033                         std::deque<std::string> params;
3034                         params.push_back(":"+reason);
3035                         DoOneToMany(user->nick,"QUIT",params);
3036                 }
3037                 // Regardless, We need to modify the user Counts..
3038                 TreeServer* SourceServer = FindServer(user->server);
3039                 if (SourceServer) {
3040                         SourceServer->DelUserCount();
3041                 }
3042
3043         }
3044
3045         virtual void OnUserPostNick(userrec* user, std::string oldnick)
3046         {
3047                 if (user->fd > -1)
3048                 {
3049                         std::deque<std::string> params;
3050                         params.push_back(user->nick);
3051                         DoOneToMany(oldnick,"NICK",params);
3052                 }
3053         }
3054
3055         virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
3056         {
3057                 if ((source) && (source->fd > -1))
3058                 {
3059                         std::deque<std::string> params;
3060                         params.push_back(chan->name);
3061                         params.push_back(user->nick);
3062                         params.push_back(":"+reason);
3063                         DoOneToMany(source->nick,"KICK",params);
3064                 }
3065         }
3066
3067         virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
3068         {
3069                 std::deque<std::string> params;
3070                 params.push_back(dest->nick);
3071                 params.push_back(":"+reason);
3072                 DoOneToMany(source->nick,"KILL",params);
3073         }
3074
3075         virtual void OnRehash(std::string parameter)
3076         {
3077                 if (parameter != "")
3078                 {
3079                         std::deque<std::string> params;
3080                         params.push_back(parameter);
3081                         DoOneToMany(Srv->GetServerName(),"REHASH",params);
3082                         // check for self
3083                         if (Srv->MatchText(Srv->GetServerName(),parameter))
3084                         {
3085                                 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
3086                                 Srv->RehashServer();
3087                         }
3088                 }
3089                 ReadConfiguration(false);
3090         }
3091
3092         // note: the protocol does not allow direct umode +o except
3093         // via NICK with 8 params. sending OPERTYPE infers +o modechange
3094         // locally.
3095         virtual void OnOper(userrec* user, std::string opertype)
3096         {
3097                 if (user->fd > -1)
3098                 {
3099                         std::deque<std::string> params;
3100                         params.push_back(opertype);
3101                         DoOneToMany(user->nick,"OPERTYPE",params);
3102                 }
3103         }
3104
3105         void OnLine(userrec* source, std::string host, bool adding, char linetype, long duration, std::string reason)
3106         {
3107                 if (source->fd > -1)
3108                 {
3109                         char type[8];
3110                         snprintf(type,8,"%cLINE",linetype);
3111                         std::string stype = type;
3112                         if (adding)
3113                         {
3114                                 char sduration[MAXBUF];
3115                                 snprintf(sduration,MAXBUF,"%ld",duration);
3116                                 std::deque<std::string> params;
3117                                 params.push_back(host);
3118                                 params.push_back(sduration);
3119                                 params.push_back(":"+reason);
3120                                 DoOneToMany(source->nick,stype,params);
3121                         }
3122                         else
3123                         {
3124                                 std::deque<std::string> params;
3125                                 params.push_back(host);
3126                                 DoOneToMany(source->nick,stype,params);
3127                         }
3128                 }
3129         }
3130
3131         virtual void OnAddGLine(long duration, userrec* source, std::string reason, std::string hostmask)
3132         {
3133                 OnLine(source,hostmask,true,'G',duration,reason);
3134         }
3135         
3136         virtual void OnAddZLine(long duration, userrec* source, std::string reason, std::string ipmask)
3137         {
3138                 OnLine(source,ipmask,true,'Z',duration,reason);
3139         }
3140
3141         virtual void OnAddQLine(long duration, userrec* source, std::string reason, std::string nickmask)
3142         {
3143                 OnLine(source,nickmask,true,'Q',duration,reason);
3144         }
3145
3146         virtual void OnAddELine(long duration, userrec* source, std::string reason, std::string hostmask)
3147         {
3148                 OnLine(source,hostmask,true,'E',duration,reason);
3149         }
3150
3151         virtual void OnDelGLine(userrec* source, std::string hostmask)
3152         {
3153                 OnLine(source,hostmask,false,'G',0,"");
3154         }
3155
3156         virtual void OnDelZLine(userrec* source, std::string ipmask)
3157         {
3158                 OnLine(source,ipmask,false,'Z',0,"");
3159         }
3160
3161         virtual void OnDelQLine(userrec* source, std::string nickmask)
3162         {
3163                 OnLine(source,nickmask,false,'Q',0,"");
3164         }
3165
3166         virtual void OnDelELine(userrec* source, std::string hostmask)
3167         {
3168                 OnLine(source,hostmask,false,'E',0,"");
3169         }
3170
3171         virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
3172         {
3173                 if ((user->fd > -1) && (user->registered == 7))
3174                 {
3175                         if (target_type == TYPE_USER)
3176                         {
3177                                 userrec* u = (userrec*)dest;
3178                                 std::deque<std::string> params;
3179                                 params.push_back(u->nick);
3180                                 params.push_back(text);
3181                                 DoOneToMany(user->nick,"MODE",params);
3182                         }
3183                         else
3184                         {
3185                                 chanrec* c = (chanrec*)dest;
3186                                 std::deque<std::string> params;
3187                                 params.push_back(c->name);
3188                                 params.push_back(text);
3189                                 DoOneToMany(user->nick,"MODE",params);
3190                         }
3191                 }
3192         }
3193
3194         virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
3195         {
3196                 TreeSocket* s = (TreeSocket*)opaque;
3197                 if (target)
3198                 {
3199                         if (target_type == TYPE_USER)
3200                         {
3201                                 userrec* u = (userrec*)target;
3202                                 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
3203                         }
3204                         else
3205                         {
3206                                 chanrec* c = (chanrec*)target;
3207                                 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
3208                         }
3209                 }
3210         }
3211
3212         virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, std::string extname, std::string extdata)
3213         {
3214                 TreeSocket* s = (TreeSocket*)opaque;
3215                 if (target)
3216                 {
3217                         if (target_type == TYPE_USER)
3218                         {
3219                                 userrec* u = (userrec*)target;
3220                                 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+u->nick+" "+extname+" :"+extdata);
3221                         }
3222                         else
3223                         {
3224                                 chanrec* c = (chanrec*)target;
3225                                 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+c->name+" "+extname+" :"+extdata);
3226                         }
3227                 }
3228         }
3229
3230         virtual ~ModuleSpanningTree()
3231         {
3232         }
3233
3234         virtual Version GetVersion()
3235         {
3236                 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
3237         }
3238
3239         void Implements(char* List)
3240         {
3241                 List[I_OnPreCommand] = List[I_OnGetServerDescription] = List[I_OnUserInvite] = List[I_OnPostLocalTopicChange] = 1;
3242                 List[I_OnWallops] = List[I_OnUserNotice] = List[I_OnUserMessage] = List[I_OnBackgroundTimer] = 1;
3243                 List[I_OnUserJoin] = List[I_OnChangeHost] = List[I_OnChangeName] = List[I_OnUserPart] = List[I_OnUserConnect] = 1;
3244                 List[I_OnUserQuit] = List[I_OnUserPostNick] = List[I_OnUserKick] = List[I_OnRemoteKill] = List[I_OnRehash] = 1;
3245                 List[I_OnOper] = List[I_OnAddGLine] = List[I_OnAddZLine] = List[I_OnAddQLine] = List[I_OnAddELine] = 1;
3246                 List[I_OnDelGLine] = List[I_OnDelZLine] = List[I_OnDelQLine] = List[I_OnDelELine] = List[I_ProtoSendMode] = List[I_OnMode] = 1;
3247                 List[I_OnStats] = List[I_ProtoSendMetaData] = 1;
3248         }
3249
3250         /* It is IMPORTANT that m_spanningtree is the last module in the chain
3251          * so that any activity it sees is FINAL, e.g. we arent going to send out
3252          * a NICK message before m_cloaking has finished putting the +x on the user,
3253          * etc etc.
3254          * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
3255          * the module call queue.
3256          */
3257         Priority Prioritize()
3258         {
3259                 return PRIORITY_LAST;
3260         }
3261 };
3262
3263
3264 class ModuleSpanningTreeFactory : public ModuleFactory
3265 {
3266  public:
3267         ModuleSpanningTreeFactory()
3268         {
3269         }
3270         
3271         ~ModuleSpanningTreeFactory()
3272         {
3273         }
3274         
3275         virtual Module * CreateModule(Server* Me)
3276         {
3277                 TreeProtocolModule = new ModuleSpanningTree(Me);
3278                 return TreeProtocolModule;
3279         }
3280         
3281 };
3282
3283
3284 extern "C" void * init_module( void )
3285 {
3286         return new ModuleSpanningTreeFactory;
3287 }