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