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