]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree.cpp
34d1c7091806e4f1e3f38797a3fbdc85fb31a4cd
[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 #include "hash_map.h"
27 #include "configreader.h"
28 #include "users.h"
29 #include "channels.h"
30 #include "modules.h"
31 #include "commands.h"
32 #include "commands/cmd_whois.h"
33 #include "commands/cmd_stats.h"
34 #include "socket.h"
35 #include "helperfuncs.h"
36 #include "inspircd.h"
37 #include "inspstring.h"
38 #include "hashcomp.h"
39 #include "message.h"
40 #include "xline.h"
41 #include "typedefs.h"
42 #include "cull_list.h"
43 #include "aes.h"
44
45 #define nspace __gnu_cxx
46
47 /*
48  * The server list in InspIRCd is maintained as two structures
49  * which hold the data in different ways. Most of the time, we
50  * want to very quicky obtain three pieces of information:
51  *
52  * (1) The information on a server
53  * (2) The information on the server we must send data through
54  *     to actually REACH the server we're after
55  * (3) Potentially, the child/parent objects of this server
56  *
57  * The InspIRCd spanning protocol provides easy access to these
58  * by storing the data firstly in a recursive structure, where
59  * each item references its parent item, and a dynamic list
60  * of child items, and another structure which stores the items
61  * hashed, linearly. This means that if we want to find a server
62  * by name quickly, we can look it up in the hash, avoiding
63  * any O(n) lookups. If however, during a split or sync, we want
64  * to apply an operation to a server, and any of its child objects
65  * we can resort to recursion to walk the tree structure.
66  */
67
68 class ModuleSpanningTree;
69 static ModuleSpanningTree* TreeProtocolModule;
70
71 extern ServerConfig* Config;
72 extern InspIRCd* ServerInstance;
73 extern std::vector<Module*> modules;
74 extern std::vector<ircd_module*> factory;
75 extern int MODCOUNT;
76
77 /* Any socket can have one of five states at any one time.
78  * The LISTENER state indicates a socket which is listening
79  * for connections. It cannot receive data itself, only incoming
80  * sockets.
81  * The CONNECTING state indicates an outbound socket which is
82  * waiting to be writeable.
83  * The WAIT_AUTH_1 state indicates the socket is outbound and
84  * has successfully connected, but has not yet sent and received
85  * SERVER strings.
86  * The WAIT_AUTH_2 state indicates that the socket is inbound
87  * (allocated by a LISTENER) but has not yet sent and received
88  * SERVER strings.
89  * The CONNECTED state represents a fully authorized, fully
90  * connected server.
91  */
92 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
93
94 /* We need to import these from the core for use in netbursts */
95 extern user_hash clientlist;
96 extern chan_hash chanlist;
97
98 /* Foward declarations */
99 class TreeServer;
100 class TreeSocket;
101
102 /* This variable represents the root of the server tree
103  * (for all intents and purposes, it's us)
104  */
105 TreeServer *TreeRoot;
106
107 static Server* Srv;
108
109 /* This hash_map holds the hash equivalent of the server
110  * tree, used for rapid linear lookups.
111  */
112 typedef nspace::hash_map<std::string, TreeServer*, nspace::hash<string>, irc::StrHashComp> server_hash;
113 server_hash serverlist;
114
115 typedef nspace::hash_map<std::string, userrec*> uid_hash;
116 typedef nspace::hash_map<std::string, char*> sid_hash;
117
118 /* More forward declarations */
119 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> &params, std::string target);
120 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> &params, std::string omit);
121 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> &params);
122 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, irc::string command, std::deque<std::string> &params);
123 void ReadConfiguration(bool rebind);
124
125 /* Flatten links and /MAP for non-opers */
126 bool FlatLinks;
127 /* Hide U-Lined servers in /MAP and /LINKS */
128 bool HideULines;
129
130 /* Imported from xline.cpp for use during netburst */
131 extern std::vector<KLine> klines;
132 extern std::vector<GLine> glines;
133 extern std::vector<ZLine> zlines;
134 extern std::vector<QLine> qlines;
135 extern std::vector<ELine> elines;
136 extern std::vector<KLine> pklines;
137 extern std::vector<GLine> pglines;
138 extern std::vector<ZLine> pzlines;
139 extern std::vector<QLine> pqlines;
140 extern std::vector<ELine> pelines;
141
142 std::vector<std::string> ValidIPs;
143
144 class UserManager : public classbase
145 {
146         uid_hash uids;
147         sid_hash sids;
148  public:
149         UserManager()
150         {
151                 uids.clear();
152                 sids.clear();
153         }
154
155         std::string UserToUID(userrec* user)
156         {
157                 return "";
158         }
159
160         std::string UIDToUser(const std::string &UID)
161         {
162                 return "";
163         }
164
165         std::string CreateAndAdd(userrec* user)
166         {
167                 return "";
168         }
169
170         std::string CreateAndAdd(const std::string &servername)
171         {
172                 return "";
173         }
174
175         std::string ServerToSID(const std::string &servername)
176         {
177                 return "";
178         }
179
180         std::string SIDToServer(const std::string &SID)
181         {
182                 return "";
183         }
184
185         userrec* FindByID(const std::string &UID)
186         {
187                 return NULL;
188         }
189 };
190
191
192 /* Each server in the tree is represented by one class of
193  * type TreeServer. A locally connected TreeServer can
194  * have a class of type TreeSocket associated with it, for
195  * remote servers, the TreeSocket entry will be NULL.
196  * Each server also maintains a pointer to its parent
197  * (NULL if this server is ours, at the top of the tree)
198  * and a pointer to its "Route" (see the comments in the
199  * constructors below), and also a dynamic list of pointers
200  * to its children which can be iterated recursively
201  * if required. Creating or deleting objects of type
202  i* TreeServer automatically maintains the hash_map of
203  * TreeServer items, deleting and inserting them as they
204  * are created and destroyed.
205  */
206
207 class TreeServer : public classbase
208 {
209         TreeServer* Parent;                     /* Parent entry */
210         TreeServer* Route;                      /* Route entry */
211         std::vector<TreeServer*> Children;      /* List of child objects */
212         irc::string ServerName;                 /* Server's name */
213         std::string ServerDesc;                 /* Server's description */
214         std::string VersionString;              /* Version string or empty string */
215         int UserCount;                          /* Not used in this version */
216         int OperCount;                          /* Not used in this version */
217         TreeSocket* Socket;                     /* For directly connected servers this points at the socket object */
218         time_t NextPing;                        /* After this time, the server should be PINGed*/
219         bool LastPingWasGood;                   /* True if the server responded to the last PING with a PONG */
220         
221  public:
222
223         /* We don't use this constructor. Its a dummy, and won't cause any insertion
224          * of the TreeServer into the hash_map. See below for the two we DO use.
225          */
226         TreeServer()
227         {
228                 Parent = NULL;
229                 ServerName = "";
230                 ServerDesc = "";
231                 VersionString = "";
232                 UserCount = OperCount = 0;
233                 VersionString = Srv->GetVersion();
234         }
235
236         /* We use this constructor only to create the 'root' item, TreeRoot, which
237          * represents our own server. Therefore, it has no route, no parent, and
238          * no socket associated with it. Its version string is our own local version.
239          */
240         TreeServer(std::string Name, std::string Desc) : ServerName(Name.c_str()), ServerDesc(Desc)
241         {
242                 Parent = NULL;
243                 VersionString = "";
244                 UserCount = OperCount = 0;
245                 VersionString = Srv->GetVersion();
246                 Route = NULL;
247                 Socket = NULL; /* Fix by brain */
248                 AddHashEntry();
249         }
250
251         /* When we create a new server, we call this constructor to initialize it.
252          * This constructor initializes the server's Route and Parent, and sets up
253          * its ping counters so that it will be pinged one minute from now.
254          */
255         TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name.c_str()), ServerDesc(Desc), Socket(Sock)
256         {
257                 VersionString = "";
258                 UserCount = OperCount = 0;
259                 this->SetNextPingTime(time(NULL) + 120);
260                 this->SetPingFlag();
261
262                 /* find the 'route' for this server (e.g. the one directly connected
263                  * to the local server, which we can use to reach it)
264                  *
265                  * In the following example, consider we have just added a TreeServer
266                  * class for server G on our network, of which we are server A.
267                  * To route traffic to G (marked with a *) we must send the data to
268                  * B (marked with a +) so this algorithm initializes the 'Route'
269                  * value to point at whichever server traffic must be routed through
270                  * to get here. If we were to try this algorithm with server B,
271                  * the Route pointer would point at its own object ('this').
272                  *
273                  *              A
274                  *             / \
275                  *          + B   C
276                  *           / \   \
277                  *          D   E   F
278                  *         /         \
279                  *      * G           H
280                  *
281                  * We only run this algorithm when a server is created, as
282                  * the routes remain constant while ever the server exists, and
283                  * do not need to be re-calculated.
284                  */
285
286                 Route = Above;
287                 if (Route == TreeRoot)
288                 {
289                         Route = this;
290                 }
291                 else
292                 {
293                         while (this->Route->GetParent() != TreeRoot)
294                         {
295                                 this->Route = Route->GetParent();
296                         }
297                 }
298
299                 /* Because recursive code is slow and takes a lot of resources,
300                  * we store two representations of the server tree. The first
301                  * is a recursive structure where each server references its
302                  * children and its parent, which is used for netbursts and
303                  * netsplits to dump the whole dataset to the other server,
304                  * and the second is used for very fast lookups when routing
305                  * messages and is instead a hash_map, where each item can
306                  * be referenced by its server name. The AddHashEntry()
307                  * call below automatically inserts each TreeServer class
308                  * into the hash_map as it is created. There is a similar
309                  * maintainance call in the destructor to tidy up deleted
310                  * servers.
311                  */
312
313                 this->AddHashEntry();
314         }
315
316         int QuitUsers(const std::string &reason)
317         {
318                 log(DEBUG,"Removing all users from server %s",this->ServerName.c_str());
319                 const char* reason_s = reason.c_str();
320                 std::vector<userrec*> time_to_die;
321                 for (user_hash::iterator n = clientlist.begin(); n != clientlist.end(); n++)
322                 {
323                         if (!strcmp(n->second->server, this->ServerName.c_str()))
324                         {
325                                 time_to_die.push_back(n->second);
326                         }
327                 }
328                 for (std::vector<userrec*>::iterator n = time_to_die.begin(); n != time_to_die.end(); n++)
329                 {
330                         userrec* a = (userrec*)*n;
331                         log(DEBUG,"Kill %s fd=%d",a->nick,a->fd);
332                         if (!IS_LOCAL(a))
333                                 kill_link(a,reason_s);
334                 }
335                 return time_to_die.size();
336         }
337
338         /* This method is used to add the structure to the
339          * hash_map for linear searches. It is only called
340          * by the constructors.
341          */
342         void AddHashEntry()
343         {
344                 server_hash::iterator iter;
345                 iter = serverlist.find(this->ServerName.c_str());
346                 if (iter == serverlist.end())
347                         serverlist[this->ServerName.c_str()] = this;
348         }
349
350         /* This method removes the reference to this object
351          * from the hash_map which is used for linear searches.
352          * It is only called by the default destructor.
353          */
354         void DelHashEntry()
355         {
356                 server_hash::iterator iter;
357                 iter = serverlist.find(this->ServerName.c_str());
358                 if (iter != serverlist.end())
359                         serverlist.erase(iter);
360         }
361
362         /* These accessors etc should be pretty self-
363          * explanitory.
364          */
365
366         TreeServer* GetRoute()
367         {
368                 return Route;
369         }
370
371         std::string GetName()
372         {
373                 return ServerName.c_str();
374         }
375
376         std::string GetDesc()
377         {
378                 return ServerDesc;
379         }
380
381         std::string GetVersion()
382         {
383                 return VersionString;
384         }
385
386         void SetNextPingTime(time_t t)
387         {
388                 this->NextPing = t;
389                 LastPingWasGood = false;
390         }
391
392         time_t NextPingTime()
393         {
394                 return NextPing;
395         }
396
397         bool AnsweredLastPing()
398         {
399                 return LastPingWasGood;
400         }
401
402         void SetPingFlag()
403         {
404                 LastPingWasGood = true;
405         }
406
407         int GetUserCount()
408         {
409                 return UserCount;
410         }
411
412         void AddUserCount()
413         {
414                 UserCount++;
415         }
416
417         void DelUserCount()
418         {
419                 UserCount--;
420         }
421
422         int GetOperCount()
423         {
424                 return OperCount;
425         }
426
427         TreeSocket* GetSocket()
428         {
429                 return Socket;
430         }
431
432         TreeServer* GetParent()
433         {
434                 return Parent;
435         }
436
437         void SetVersion(std::string Version)
438         {
439                 VersionString = Version;
440         }
441
442         unsigned int ChildCount()
443         {
444                 return Children.size();
445         }
446
447         TreeServer* GetChild(unsigned int n)
448         {
449                 if (n < Children.size())
450                 {
451                         /* Make sure they  cant request
452                          * an out-of-range object. After
453                          * all we know what these programmer
454                          * types are like *grin*.
455                          */
456                         return Children[n];
457                 }
458                 else
459                 {
460                         return NULL;
461                 }
462         }
463
464         void AddChild(TreeServer* Child)
465         {
466                 Children.push_back(Child);
467         }
468
469         bool DelChild(TreeServer* Child)
470         {
471                 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
472                 {
473                         if (*a == Child)
474                         {
475                                 Children.erase(a);
476                                 return true;
477                         }
478                 }
479                 return false;
480         }
481
482         /* Removes child nodes of this node, and of that node, etc etc.
483          * This is used during netsplits to automatically tidy up the
484          * server tree. It is slow, we don't use it for much else.
485          */
486         bool Tidy()
487         {
488                 bool stillchildren = true;
489                 while (stillchildren)
490                 {
491                         stillchildren = false;
492                         for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
493                         {
494                                 TreeServer* s = (TreeServer*)*a;
495                                 s->Tidy();
496                                 Children.erase(a);
497                                 DELETE(s);
498                                 stillchildren = true;
499                                 break;
500                         }
501                 }
502                 return true;
503         }
504
505         ~TreeServer()
506         {
507                 /* We'd better tidy up after ourselves, eh? */
508                 this->DelHashEntry();
509         }
510 };
511
512 /* The Link class might as well be a struct,
513  * but this is C++ and we don't believe in structs (!).
514  * It holds the entire information of one <link>
515  * tag from the main config file. We maintain a list
516  * of them, and populate the list on rehash/load.
517  */
518
519 class Link : public classbase
520 {
521  public:
522          irc::string Name;
523          std::string IPAddr;
524          int Port;
525          std::string SendPass;
526          std::string RecvPass;
527          unsigned long AutoConnect;
528          time_t NextConnectTime;
529          std::string EncryptionKey;
530          bool HiddenFromStats;
531 };
532
533 /* The usual stuff for inspircd modules,
534  * plus the vector of Link classes which we
535  * use to store the <link> tags from the config
536  * file.
537  */
538 ConfigReader *Conf;
539 std::vector<Link> LinkBlocks;
540
541 /* Yay for fast searches!
542  * This is hundreds of times faster than recursion
543  * or even scanning a linked list, especially when
544  * there are more than a few servers to deal with.
545  * (read as: lots).
546  */
547 TreeServer* FindServer(std::string ServerName)
548 {
549         server_hash::iterator iter;
550         iter = serverlist.find(ServerName.c_str());
551         if (iter != serverlist.end())
552         {
553                 return iter->second;
554         }
555         else
556         {
557                 return NULL;
558         }
559 }
560
561 /* Returns the locally connected server we must route a
562  * message through to reach server 'ServerName'. This
563  * only applies to one-to-one and not one-to-many routing.
564  * See the comments for the constructor of TreeServer
565  * for more details.
566  */
567 TreeServer* BestRouteTo(std::string ServerName)
568 {
569         if (ServerName.c_str() == TreeRoot->GetName())
570                 return NULL;
571         TreeServer* Found = FindServer(ServerName);
572         if (Found)
573         {
574                 return Found->GetRoute();
575         }
576         else
577         {
578                 return NULL;
579         }
580 }
581
582 /* Find the first server matching a given glob mask.
583  * Theres no find-using-glob method of hash_map [awwww :-(]
584  * so instead, we iterate over the list using an iterator
585  * and match each one until we get a hit. Yes its slow,
586  * deal with it.
587  */
588 TreeServer* FindServerMask(std::string ServerName)
589 {
590         for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
591         {
592                 if (Srv->MatchText(i->first.c_str(),ServerName))
593                         return i->second;
594         }
595         return NULL;
596 }
597
598 /* A convenient wrapper that returns true if a server exists */
599 bool IsServer(std::string ServerName)
600 {
601         return (FindServer(ServerName) != NULL);
602 }
603
604
605 class cmd_rconnect : public command_t
606 {
607         Module* Creator;
608  public:
609         cmd_rconnect (Module* Callback) : command_t("RCONNECT", 'o', 2), Creator(Callback)
610         {
611                 this->source = "m_spanningtree.so";
612                 syntax = "<remote-server-mask> <servermask>";
613         }
614
615         void Handle (const char** parameters, int pcnt, userrec *user)
616         {
617                 WriteServ(user->fd,"NOTICE %s :*** RCONNECT: Sending remote connect to \002%s\002 to connect server \002%s\002.",user->nick,parameters[0],parameters[1]);
618                 /* Is this aimed at our server? */
619                 if (Srv->MatchText(Srv->GetServerName(),parameters[0]))
620                 {
621                         /* Yes, initiate the given connect */
622                         WriteOpers("*** Remote CONNECT from %s matching \002%s\002, connecting server \002%s\002",user->nick,parameters[0],parameters[1]);
623                         const char* para[1];
624                         para[0] = parameters[1];
625                         Creator->OnPreCommand("CONNECT", para, 1, user, true);
626                 }
627         }
628 };
629  
630
631
632 /* Every SERVER connection inbound or outbound is represented by
633  * an object of type TreeSocket.
634  * TreeSockets, being inherited from InspSocket, can be tied into
635  * the core socket engine, and we cn therefore receive activity events
636  * for them, just like activex objects on speed. (yes really, that
637  * is a technical term!) Each of these which relates to a locally
638  * connected server is assocated with it, by hooking it onto a
639  * TreeSocket class using its constructor. In this way, we can
640  * maintain a list of servers, some of which are directly connected,
641  * some of which are not.
642  */
643
644 class TreeSocket : public InspSocket
645 {
646         std::string myhost;
647         std::string in_buffer;
648         ServerState LinkState;
649         std::string InboundServerName;
650         std::string InboundDescription;
651         int num_lost_users;
652         int num_lost_servers;
653         time_t NextPing;
654         bool LastPingWasGood;
655         bool bursting;
656         AES* ctx_in;
657         AES* ctx_out;
658         unsigned int keylength;
659         
660  public:
661
662         /* Because most of the I/O gubbins are encapsulated within
663          * InspSocket, we just call the superclass constructor for
664          * most of the action, and append a few of our own values
665          * to it.
666          */
667         TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
668                 : InspSocket(host, port, listening, maxtime)
669         {
670                 myhost = host;
671                 this->LinkState = LISTENER;
672                 this->ctx_in = NULL;
673                 this->ctx_out = NULL;
674         }
675
676         TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
677                 : InspSocket(host, port, listening, maxtime)
678         {
679                 myhost = ServerName;
680                 this->LinkState = CONNECTING;
681                 this->ctx_in = NULL;
682                 this->ctx_out = NULL;
683         }
684
685         /* When a listening socket gives us a new file descriptor,
686          * we must associate it with a socket without creating a new
687          * connection. This constructor is used for this purpose.
688          */
689         TreeSocket(int newfd, char* ip)
690                 : InspSocket(newfd, ip)
691         {
692                 this->LinkState = WAIT_AUTH_1;
693                 this->ctx_in = NULL;
694                 this->ctx_out = NULL;
695                 this->SendCapabilities();
696         }
697
698         ~TreeSocket()
699         {
700                 if (ctx_in)
701                         DELETE(ctx_in);
702                 if (ctx_out)
703                         DELETE(ctx_out);
704         }
705
706         void InitAES(std::string key,std::string SName)
707         {
708                 if (key == "")
709                         return;
710
711                 ctx_in = new AES();
712                 ctx_out = new AES();
713                 log(DEBUG,"Initialized AES key %s",key.c_str());
714                 // key must be 16, 24, 32 etc bytes (multiple of 8)
715                 keylength = key.length();
716                 if (!(keylength == 16 || keylength == 24 || keylength == 32))
717                 {
718                         WriteOpers("*** \2ERROR\2: Key length for encryptionkey is not 16, 24 or 32 bytes in length!");
719                         log(DEBUG,"Key length not 16, 24 or 32 characters!");
720                 }
721                 else
722                 {
723                         WriteOpers("*** \2AES\2: Initialized %d bit encryption to server %s",keylength*8,SName.c_str());
724                         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\
725                                 \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);
726                         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\
727                                 \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);
728                 }
729         }
730         
731         /* When an outbound connection finishes connecting, we receive
732          * this event, and must send our SERVER string to the other
733          * side. If the other side is happy, as outlined in the server
734          * to server docs on the inspircd.org site, the other side
735          * will then send back its own server string.
736          */
737         virtual bool OnConnected()
738         {
739                 if (this->LinkState == CONNECTING)
740                 {
741                         /* we do not need to change state here. */
742                         for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
743                         {
744                                 if (x->Name == this->myhost)
745                                 {
746                                         Srv->SendOpers("*** Connection to \2"+myhost+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] established.");
747                                         this->SendCapabilities();
748                                         if (x->EncryptionKey != "")
749                                         {
750                                                 if (!(x->EncryptionKey.length() == 16 || x->EncryptionKey.length() == 24 || x->EncryptionKey.length() == 32))
751                                                 {
752                                                         WriteOpers("\2WARNING\2: Your encryption key is NOT 16, 24 or 32 characters in length, encryption will \2NOT\2 be enabled.");
753                                                 }
754                                                 else
755                                                 {
756                                                         this->WriteLine("AES "+Srv->GetServerName());
757                                                         this->InitAES(x->EncryptionKey,x->Name.c_str());
758                                                 }
759                                         }
760                                         /* found who we're supposed to be connecting to, send the neccessary gubbins. */
761                                         this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
762                                         return true;
763                                 }
764                         }
765                 }
766                 /* There is a (remote) chance that between the /CONNECT and the connection
767                  * being accepted, some muppet has removed the <link> block and rehashed.
768                  * If that happens the connection hangs here until it's closed. Unlikely
769                  * and rather harmless.
770                  */
771                 Srv->SendOpers("*** Connection to \2"+myhost+"\2 lost link tag(!)");
772                 return true;
773         }
774         
775         virtual void OnError(InspSocketError e)
776         {
777                 /* We don't handle this method, because all our
778                  * dirty work is done in OnClose() (see below)
779                  * which is still called on error conditions too.
780                  */
781                 if (e == I_ERR_CONNECT)
782                 {
783                         Srv->SendOpers("*** Connection failed: Connection refused");
784                 }
785         }
786
787         virtual int OnDisconnect()
788         {
789                 /* For the same reason as above, we don't
790                  * handle OnDisconnect()
791                  */
792                 return true;
793         }
794
795         /* Recursively send the server tree with distances as hops.
796          * This is used during network burst to inform the other server
797          * (and any of ITS servers too) of what servers we know about.
798          * If at any point any of these servers already exist on the other
799          * end, our connection may be terminated. The hopcounts given
800          * by this function are relative, this doesn't matter so long as
801          * they are all >1, as all the remote servers re-calculate them
802          * to be relative too, with themselves as hop 0.
803          */
804         void SendServers(TreeServer* Current, TreeServer* s, int hops)
805         {
806                 char command[1024];
807                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
808                 {
809                         TreeServer* recursive_server = Current->GetChild(q);
810                         if (recursive_server != s)
811                         {
812                                 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
813                                 this->WriteLine(command);
814                                 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
815                                 /* down to next level */
816                                 this->SendServers(recursive_server, s, hops+1);
817                         }
818                 }
819         }
820
821         std::string MyCapabilities()
822         {
823                 ServerConfig* Config = Srv->GetConfig();
824                 std::vector<std::string> modlist;
825                 std::string capabilities = "";
826
827                 for (int i = 0; i <= MODCOUNT; i++)
828                 {
829                         if ((modules[i]->GetVersion().Flags & VF_STATIC) || (modules[i]->GetVersion().Flags & VF_COMMON))
830                                 modlist.push_back(Config->module_names[i]);
831                 }
832                 sort(modlist.begin(),modlist.end());
833                 for (unsigned int i = 0; i < modlist.size(); i++)
834                 {
835                         if (i)
836                                 capabilities = capabilities + ",";
837                         capabilities = capabilities + modlist[i];
838                 }
839                 return capabilities;
840         }
841         
842         void SendCapabilities()
843         {
844                 this->WriteLine("CAPAB "+MyCapabilities());
845         }
846
847         bool Capab(std::deque<std::string> params)
848         {
849                 if (params.size() != 1)
850                 {
851                         this->WriteLine("ERROR :Invalid number of parameters for CAPAB");
852                         return false;
853                 }
854
855                 if (params[0] != this->MyCapabilities())
856                 {
857                         std::string quitserver = this->myhost;
858                         if (this->InboundServerName != "")
859                         {
860                                 quitserver = this->InboundServerName;
861                         }
862
863                         WriteOpers("*** \2ERROR\2: Server '%s' does not have the same set of modules loaded, cannot link!",quitserver.c_str());
864                         WriteOpers("*** Our networked module set is: '%s'",this->MyCapabilities().c_str());
865                         WriteOpers("*** Other server's networked module set is: '%s'",params[0].c_str());
866                         WriteOpers("*** These lists must match exactly on both servers. Please correct these errors, and try again.");
867                         this->WriteLine("ERROR :CAPAB mismatch; My capabilities: '"+this->MyCapabilities()+"'");
868                         return false;
869                 }
870
871                 return true;
872         }
873
874         /* This function forces this server to quit, removing this server
875          * and any users on it (and servers and users below that, etc etc).
876          * It's very slow and pretty clunky, but luckily unless your network
877          * is having a REAL bad hair day, this function shouldnt be called
878          * too many times a month ;-)
879          */
880         void SquitServer(std::string &from, TreeServer* Current)
881         {
882                 /* recursively squit the servers attached to 'Current'.
883                  * We're going backwards so we don't remove users
884                  * while we still need them ;)
885                  */
886                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
887                 {
888                         TreeServer* recursive_server = Current->GetChild(q);
889                         this->SquitServer(from,recursive_server);
890                 }
891                 /* Now we've whacked the kids, whack self */
892                 num_lost_servers++;
893                 num_lost_users += Current->QuitUsers(from);
894         }
895
896         /* This is a wrapper function for SquitServer above, which
897          * does some validation first and passes on the SQUIT to all
898          * other remaining servers.
899          */
900         void Squit(TreeServer* Current,std::string reason)
901         {
902                 if ((Current) && (Current != TreeRoot))
903                 {
904                         std::deque<std::string> params;
905                         params.push_back(Current->GetName());
906                         params.push_back(":"+reason);
907                         DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
908                         if (Current->GetParent() == TreeRoot)
909                         {
910                                 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
911                         }
912                         else
913                         {
914                                 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
915                         }
916                         num_lost_servers = 0;
917                         num_lost_users = 0;
918                         std::string from = Current->GetParent()->GetName()+" "+Current->GetName();
919                         SquitServer(from, Current);
920                         Current->Tidy();
921                         Current->GetParent()->DelChild(Current);
922                         DELETE(Current);
923                         WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
924                 }
925                 else
926                 {
927                         log(DEFAULT,"Squit from unknown server");
928                 }
929         }
930
931         /* FMODE command - server mode with timestamp checks */
932         bool ForceMode(std::string source, std::deque<std::string> &params)
933         {
934                 /* Chances are this is a 1.0 FMODE without TS */
935                 if (params.size() < 3)
936                 {
937                         this->WriteLine("ERROR :Version 1.0 FMODE sent to version 1.1 server");
938                         return false;
939                 }
940                 
941                 bool smode = false;
942                 std::string sourceserv;
943
944                 /* Are we dealing with an FMODE from a user, or from a server? */
945                 userrec* who = Srv->FindNick(source);
946                 if (who)
947                 {
948                         /* FMODE from a user, set sourceserv to the users server name */
949                         sourceserv = who->server;
950                 }
951                 else
952                 {
953                         /* FMODE from a server, create a fake user to receive mode feedback */
954                         who = new userrec();
955                         who->fd = FD_MAGIC_NUMBER;
956                         smode = true;           /* Setting this flag tells us we should free the userrec later */
957                         sourceserv = source;    /* Set sourceserv to the actual source string */
958                 }
959                 const char* modelist[64];
960                 time_t TS = 0;
961                 int n = 0;
962                 memset(&modelist,0,sizeof(modelist));
963                 for (unsigned int q = 0; (q < params.size()) && (q < 64); q++)
964                 {
965                         if (q == 1)
966                         {
967                                 /* The timestamp is in this position.
968                                  * We don't want to pass that up to the
969                                  * server->client protocol!
970                                  */
971                                 TS = atoi(params[q].c_str());
972                         }
973                         else
974                         {
975                                 /* Everything else is fine to append to the modelist */
976                                 modelist[n++] = params[q].c_str();
977                         }
978                                 
979                 }
980                 /* Extract the TS value of the object, either userrec or chanrec */
981                 userrec* dst = Srv->FindNick(params[0]);
982                 chanrec* chan = NULL;
983                 time_t ourTS = 0;
984                 if (dst)
985                 {
986                         ourTS = dst->age;
987                 }
988                 else
989                 {
990                         chan = Srv->FindChannel(params[0]);
991                         if (chan)
992                         {
993                                 ourTS = chan->age;
994                         }
995                 }
996
997                 /* TS is equal: Merge the mode changes, use voooodoooooo on modes
998                  * with parameters.
999                  */
1000                 if (TS == ourTS)
1001                 {
1002                         log(DEBUG,"Entering TS equality check");
1003                         ModeHandler* mh = NULL;
1004                         unsigned long paramptr = 3;
1005                         std::string to_bounce = "";
1006                         std::string to_keep = "";
1007                         std::vector<std::string> params_to_keep;
1008                         std::string params_to_bounce = "";
1009                         bool adding = true;
1010                         char cur_change = 1;
1011                         char old_change = 0;
1012                         char old_bounce_change = 0;
1013                         /* Merge modes, basically do special stuff to mode with params */
1014                         for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
1015                         {
1016                                 switch (*x)
1017                                 {
1018                                         case '-':
1019                                                 adding = false;
1020                                         break;
1021                                         case '+':
1022                                                 adding = true;
1023                                         break;
1024                                         default:
1025                                                 if (adding)
1026                                                 {
1027                                                         /* We only care about whats being set,
1028                                                          * not whats being unset
1029                                                          */
1030                                                         mh = ServerInstance->ModeGrok->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1031
1032                                                         if ((mh) && (mh->GetNumParams(adding) > 0) && (!mh->IsListMode()))
1033                                                         {
1034                                                                 /* We only want to do special things to
1035                                                                  * modes with parameters, we are going to rewrite
1036                                                                  * those parameters
1037                                                                  */
1038                                                                 ModePair ret;
1039                                                                 adding ? cur_change = '+' : cur_change = '-';
1040
1041                                                                 ret = mh->ModeSet(smode ? NULL : who, dst, chan, params[paramptr]);
1042
1043                                                                 /* The mode is set here, check which we should keep */
1044                                                                 if (ret.first)
1045                                                                 {
1046                                                                         bool which_to_keep = mh->CheckTimeStamp(TS, ourTS, params[paramptr], ret.second, chan);
1047
1048                                                                         if (which_to_keep == true)
1049                                                                         {
1050                                                                                 /* Keep ours, bounce theirs:
1051                                                                                  * Send back ours to them and
1052                                                                                  * drop their mode changs
1053                                                                                  */
1054                                                                                 adding ? cur_change = '+' : cur_change = '-';
1055                                                                                 if (cur_change != old_bounce_change)
1056                                                                                         to_bounce += cur_change;
1057                                                                                 to_bounce += *x;
1058                                                                                 old_bounce_change = cur_change;
1059
1060                                                                                 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1061                                                                                         params_to_bounce.append(" ").append(ret.second);
1062                                                                         }
1063                                                                         else
1064                                                                         {
1065                                                                                 /* Keep theirs: Accept their mode change,
1066                                                                                  * do nothing else
1067                                                                                  */
1068                                                                                 adding ? cur_change = '+' : cur_change = '-';
1069                                                                                 if (cur_change != old_change)
1070                                                                                         to_keep += cur_change;
1071                                                                                 to_keep += *x;
1072                                                                                 old_change = cur_change;
1073
1074                                                                                 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1075                                                                                         params_to_keep.push_back(params[paramptr]);
1076                                                                         }
1077                                                                 }
1078                                                                 else
1079                                                                 {
1080                                                                         /* Mode isnt set here, we want it */
1081                                                                         adding ? cur_change = '+' : cur_change = '-';
1082                                                                         if (cur_change != old_change)
1083                                                                                 to_keep += cur_change;
1084                                                                         to_keep += *x;
1085                                                                         old_change = cur_change;
1086
1087                                                                         if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1088                                                                                 params_to_keep.push_back(params[paramptr]);
1089                                                                 }
1090
1091                                                                 paramptr++;
1092                                                         }
1093                                                         else
1094                                                         {
1095                                                                 mh = ServerInstance->ModeGrok->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1096
1097                                                                 if (mh)
1098                                                                 {
1099                                                                         adding ? cur_change = '+' : cur_change = '-';
1100         
1101                                                                         /* Just keep this, safe to merge with no checks
1102                                                                          * it has no parameters
1103                                                                          */
1104         
1105                                                                         if (cur_change != old_change)
1106                                                                                 to_keep += cur_change;
1107                                                                         to_keep += *x;
1108                                                                         old_change = cur_change;
1109         
1110                                                                         if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1111                                                                         {
1112                                                                                 log(DEBUG,"Mode removal %d %d",adding, mh->GetNumParams(adding));
1113                                                                                 params_to_keep.push_back(params[paramptr++]);
1114                                                                         }
1115                                                                 }
1116                                                         }
1117                                                 }
1118                                                 else
1119                                                 {
1120                                                         mh = ServerInstance->ModeGrok->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1121
1122                                                         if (mh)
1123                                                         {
1124                                                                 /* Taking a mode away */
1125                                                                 adding ? cur_change = '+' : cur_change = '-';
1126
1127                                                                 if (cur_change != old_change)
1128                                                                         to_keep += cur_change;
1129                                                                 to_keep += *x;
1130                                                                 old_change = cur_change;
1131
1132                                                                 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1133                                                                         params_to_keep.push_back(params[paramptr++]);
1134                                                         }
1135                                                 }
1136                                         break;
1137                                 }
1138                         }
1139
1140                         if (to_bounce.length())
1141                         {
1142                                 std::deque<std::string> newparams;
1143                                 newparams.push_back(params[0]);
1144                                 newparams.push_back(ConvToStr(ourTS));
1145                                 newparams.push_back(to_bounce+params_to_bounce);
1146                                 DoOneToOne(Srv->GetServerName(),"FMODE",newparams,sourceserv);
1147                         }
1148
1149                         if (to_keep.length())
1150                         {
1151                                 unsigned int n = 2;
1152                                 unsigned int q = 0;
1153                                 modelist[0] = params[0].c_str();
1154                                 modelist[1] = to_keep.c_str();
1155
1156                                 if (params_to_keep.size() > 2)
1157                                 {
1158                                         for (q = 2; (q < params_to_keep.size()) && (q < 64); q++)
1159                                         {
1160                                                 log(DEBUG,"Item %d of %d", q, params_to_keep.size());
1161                                                 modelist[n++] = params_to_keep[q].c_str();
1162                                         }
1163                                 }
1164
1165                                 if (smode)
1166                                 {
1167                                         log(DEBUG,"Send mode");
1168                                         Srv->SendMode(modelist, n+2, who);
1169                                 }
1170                                 else
1171                                 {
1172                                         log(DEBUG,"Send mode client");
1173                                         Srv->CallCommandHandler("MODE", modelist, n+2, who);
1174                                 }
1175
1176                                 /* HOT POTATO! PASS IT ON! */
1177                                 DoOneToAllButSender(source,"FMODE",params,sourceserv);
1178                         }
1179                 }
1180                 else
1181                 /* U-lined servers always win regardless of their TS */
1182                 if ((TS > ourTS) && (!Srv->IsUlined(source)))
1183                 {
1184                         /* Bounce the mode back to its sender.* We use our lower TS, so the other end
1185                          * SHOULD accept it, if its clock is right.
1186                          *
1187                          * NOTE: We should check that we arent bouncing anything thats already set at this end.
1188                          * If we are, bounce +ourmode to 'reinforce' it. This prevents desyncs.
1189                          * e.g. They send +l 50, we have +l 10 set. rather than bounce -l 50, we bounce +l 10.
1190                          *
1191                          * Thanks to jilles for pointing out this one-hell-of-an-issue before i even finished
1192                          * writing the code. It took me a while to come up with this solution.
1193                          *
1194                          * XXX: BE SURE YOU UNDERSTAND THIS CODE FULLY BEFORE YOU MESS WITH IT.
1195                          */
1196
1197                         std::deque<std::string> newparams;      /* New parameter list we send back */
1198                         newparams.push_back(params[0]);         /* Target, user or channel */
1199                         newparams.push_back(ConvToStr(ourTS));  /* Timestamp value of the target */
1200                         newparams.push_back("");                /* This contains the mode string. For now
1201                                                                  * it's empty, we fill it below.
1202                                                                  */
1203
1204                         /* Intelligent mode bouncing. Don't just invert, reinforce any modes which are already
1205                          * set to avoid a desync here.
1206                          */
1207                         std::string modebounce = "";
1208                         bool adding = true;
1209                         unsigned int t = 3;
1210                         ModeHandler* mh = NULL;
1211                         char cur_change = 1;
1212                         char old_change = 0;
1213                         for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
1214                         {
1215                                 /* Iterate over all mode chars in the sent set */
1216                                 switch (*x)
1217                                 {
1218                                         /* Adding or subtracting modes? */
1219                                         case '-':
1220                                                 adding = false;
1221                                         break;
1222                                         case '+':
1223                                                 adding = true;
1224                                         break;
1225                                         default:
1226                                                 /* Find the mode handler for this mode */
1227                                                 mh = ServerInstance->ModeGrok->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1228
1229                                                 /* Got a mode handler?
1230                                                  * This also prevents us bouncing modes we have no handler for.
1231                                                  */
1232                                                 if (mh)
1233                                                 {
1234                                                         ModePair ret;
1235                                                         std::string p = "";
1236
1237                                                         /* Does the mode require a parameter right now?
1238                                                          * If it does, fetch it if we can
1239                                                          */
1240                                                         if ((mh->GetNumParams(adding) > 0) && (t < params.size()))
1241                                                                 p = params[t++];
1242
1243                                                         /* Call the ModeSet method to determine if its set with the
1244                                                          * given parameter here or not.
1245                                                          */
1246                                                         ret = mh->ModeSet(smode ? NULL : who, dst, chan, p);
1247
1248                                                         /* XXX: Really. Dont ask.
1249                                                          * Determine from if its set combined with what the current
1250                                                          * 'state' is (adding or not) as to wether we should 'invert'
1251                                                          * or 'reinforce' the mode change
1252                                                          */
1253                                                         (!ret.first ? (adding ? cur_change = '-' : cur_change = '+') : (!adding ? cur_change = '-' : cur_change = '+'));
1254
1255                                                         /* Quickly determine if we have 'flipped' from + to -,
1256                                                          * or - to +, to prevent unneccessary +/- chars in the
1257                                                          * output string that waste bandwidth
1258                                                          */
1259                                                         if (cur_change != old_change)
1260                                                                 modebounce += cur_change;
1261                                                         old_change = cur_change;
1262
1263                                                         /* Add the mode character to the output string */
1264                                                         modebounce += mh->GetModeChar();
1265
1266                                                         /* We got a parameter back from ModeHandler::ModeSet,
1267                                                          * are we supposed to be sending one out right now?
1268                                                          */
1269                                                         if (ret.second.length())
1270                                                         {
1271                                                                 if (mh->GetNumParams(cur_change == '+') > 0)
1272                                                                         /* Yes we're supposed to be sending out
1273                                                                          * the parameter. Make sure it goes
1274                                                                          */
1275                                                                         newparams.push_back(ret.second);
1276                                                         }
1277
1278                                                 }
1279                                         break;
1280                                 }
1281                         }
1282                         
1283                         /* Update the parameters for FMODE with the new 'bounced' string */
1284                         newparams[2] = modebounce;
1285                         /* Only send it back the way it came, no need to send it anywhere else */
1286                         DoOneToOne(Srv->GetServerName(),"FMODE",newparams,sourceserv);
1287                         log(DEBUG,"FMODE bounced intelligently, our TS less than theirs and the other server is NOT a uline.");
1288                 }
1289                 else
1290                 {
1291                         log(DEBUG,"Allow modes, TS lower for sender");
1292                         /* The server was ulined, but something iffy is up with the TS.
1293                          * Sound the alarm bells!
1294                          */
1295                         if ((Srv->IsUlined(sourceserv)) && (TS > ourTS))
1296                         {
1297                                 WriteOpers("\2WARNING!\2 U-Lined server '%s' has bad TS for '%s' (accepted change): \2SYNC YOUR CLOCKS\2 to avoid this notice",sourceserv.c_str(),params[0].c_str());
1298                         }
1299                         /* Allow the mode, route it to either server or user command handling */
1300                         if (smode)
1301                                 Srv->SendMode(modelist,n,who);
1302                         else
1303                                 Srv->CallCommandHandler("MODE", modelist, n, who);
1304
1305                         /* HOT POTATO! PASS IT ON! */
1306                         DoOneToAllButSender(source,"FMODE",params,sourceserv);
1307                 }
1308                 /* Are we supposed to free the userrec? */
1309                 if (smode)
1310                         DELETE(who);
1311
1312                 return true;
1313         }
1314
1315         /* FTOPIC command */
1316         bool ForceTopic(std::string source, std::deque<std::string> &params)
1317         {
1318                 if (params.size() != 4)
1319                         return true;
1320                 time_t ts = atoi(params[1].c_str());
1321                 std::string nsource = source;
1322
1323                 chanrec* c = Srv->FindChannel(params[0]);
1324                 if (c)
1325                 {
1326                         if ((ts >= c->topicset) || (!*c->topic))
1327                         {
1328                                 std::string oldtopic = c->topic;
1329                                 strlcpy(c->topic,params[3].c_str(),MAXTOPIC);
1330                                 strlcpy(c->setby,params[2].c_str(),NICKMAX-1);
1331                                 c->topicset = ts;
1332                                 /* if the topic text is the same as the current topic,
1333                                  * dont bother to send the TOPIC command out, just silently
1334                                  * update the set time and set nick.
1335                                  */
1336                                 if (oldtopic != params[3])
1337                                 {
1338                                         userrec* user = Srv->FindNick(source);
1339                                         if (!user)
1340                                         {
1341                                                 WriteChannelWithServ(source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
1342                                         }
1343                                         else
1344                                         {
1345                                                 WriteChannel(c, user, "TOPIC %s :%s", c->name, c->topic);
1346                                                 nsource = user->server;
1347                                         }
1348                                         /* all done, send it on its way */
1349                                         params[3] = ":" + params[3];
1350                                         DoOneToAllButSender(source,"FTOPIC",params,nsource);
1351                                 }
1352                         }
1353                         
1354                 }
1355
1356                 return true;
1357         }
1358
1359         /* FJOIN, similar to unreal SJOIN */
1360         bool ForceJoin(std::string source, std::deque<std::string> &params)
1361         {
1362                 if (params.size() < 3)
1363                         return true;
1364
1365                 char first[MAXBUF];
1366                 char modestring[MAXBUF];
1367                 char* mode_users[127];
1368                 memset(&mode_users,0,sizeof(mode_users));
1369                 mode_users[0] = first;
1370                 mode_users[1] = modestring;
1371                 strcpy(modestring,"+");
1372                 unsigned int modectr = 2;
1373                 
1374                 userrec* who = NULL;
1375                 std::string channel = params[0];
1376                 time_t TS = atoi(params[1].c_str());
1377                 char* key = "";
1378                 
1379                 chanrec* chan = Srv->FindChannel(channel);
1380                 if (chan)
1381                 {
1382                         key = chan->key;
1383                 }
1384                 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
1385
1386                 /* default is a high value, which if we dont have this
1387                  * channel will let the other side apply their modes.
1388                  */
1389                 time_t ourTS = time(NULL)+600;
1390                 chanrec* us = Srv->FindChannel(channel);
1391                 if (us)
1392                 {
1393                         ourTS = us->age;
1394                 }
1395
1396                 log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
1397
1398                 /* do this first, so our mode reversals are correctly received by other servers
1399                  * if there is a TS collision.
1400                  */
1401                 DoOneToAllButSender(source,"FJOIN",params,source);
1402                 
1403                 for (unsigned int usernum = 2; usernum < params.size(); usernum++)
1404                 {
1405                         /* process one channel at a time, applying modes. */
1406                         char* usr = (char*)params[usernum].c_str();
1407                         /* Safety check just to make sure someones not sent us an FJOIN full of spaces
1408                          * (is this even possible?) */
1409                         if (usr && *usr)
1410                         {
1411                                 char permissions = *usr;
1412                                 switch (permissions)
1413                                 {
1414                                         case '@':
1415                                                 usr++;
1416                                                 mode_users[modectr++] = usr;
1417                                                 strlcat(modestring,"o",MAXBUF);
1418                                         break;
1419                                         case '%':
1420                                                 usr++;
1421                                                 mode_users[modectr++] = usr;
1422                                                 strlcat(modestring,"h",MAXBUF);
1423                                         break;
1424                                         case '+':
1425                                                 usr++;
1426                                                 mode_users[modectr++] = usr;
1427                                                 strlcat(modestring,"v",MAXBUF);
1428                                         break;
1429                                 }
1430                                 who = Srv->FindNick(usr);
1431                                 if (who)
1432                                 {
1433                                         Srv->JoinUserToChannel(who,channel,key);
1434                                         if (modectr >= (MAXMODES-1))
1435                                         {
1436                                                 /* theres a mode for this user. push them onto the mode queue, and flush it
1437                                                  * if there are more than MAXMODES to go.
1438                                                  */
1439                                                 if ((ourTS >= TS) || (Srv->IsUlined(who->server)))
1440                                                 {
1441                                                         /* We also always let u-lined clients win, no matter what the TS value */
1442                                                         log(DEBUG,"Our our channel newer than theirs, accepting their modes");
1443                                                         Srv->SendMode((const char**)mode_users,modectr,who);
1444                                                         if (ourTS != TS)
1445                                                         {
1446                                                                 log(DEFAULT,"Channel TS for %s changed from %lu to %lu",us->name,ourTS,TS);
1447                                                                 us->age = TS;
1448                                                         }
1449                                                 }
1450                                                 else
1451                                                 {
1452                                                         log(DEBUG,"Their channel newer than ours, bouncing their modes");
1453                                                         /* bouncy bouncy! */
1454                                                         std::deque<std::string> params;
1455                                                         /* modes are now being UNSET... */
1456                                                         *mode_users[1] = '-';
1457                                                         for (unsigned int x = 0; x < modectr; x++)
1458                                                         {
1459                                                                 if (x == 1)
1460                                                                 {
1461                                                                         params.push_back(ConvToStr(us->age));
1462                                                                 }
1463                                                                 params.push_back(mode_users[x]);
1464                                                                 
1465                                                         }
1466                                                         // tell everyone to bounce the modes. bad modes, bad!
1467                                                         DoOneToMany(Srv->GetServerName(),"FMODE",params);
1468                                                 }
1469                                                 strcpy(mode_users[1],"+");
1470                                                 modectr = 2;
1471                                         }
1472                                 }
1473                         }
1474                 }
1475                 /* there werent enough modes built up to flush it during FJOIN,
1476                  * or, there are a number left over. flush them out.
1477                  */
1478                 if ((modectr > 2) && (who))
1479                 {
1480                         if (ourTS >= TS)
1481                         {
1482                                 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
1483                                 Srv->SendMode((const char**)mode_users,modectr,who);
1484                                 if (ourTS != TS)
1485                                 {
1486                                         log(DEFAULT,"Channel TS for %s changed from %lu to %lu",us->name,ourTS,TS);
1487                                         us->age = TS;
1488                                 }
1489                         }
1490                         else
1491                         {
1492                                 log(DEBUG,"Their channel newer than ours, bouncing their modes");
1493                                 std::deque<std::string> params;
1494                                 *mode_users[1] = '-';
1495                                 for (unsigned int x = 0; x < modectr; x++)
1496                                 {
1497                                         if (x == 1)
1498                                         {
1499                                                 params.push_back(ConvToStr(us->age));
1500                                         }
1501                                         params.push_back(mode_users[x]);
1502                                 }
1503                                 DoOneToMany(Srv->GetServerName(),"FMODE",params);
1504                         }
1505                 }
1506                 return true;
1507         }
1508
1509         bool SyncChannelTS(std::string source, std::deque<std::string> &params)
1510         {
1511                 if (params.size() >= 2)
1512                 {
1513                         chanrec* c = Srv->FindChannel(params[0]);
1514                         if (c)
1515                         {
1516                                 time_t theirTS = atoi(params[1].c_str());
1517                                 time_t ourTS = c->age;
1518                                 if (ourTS >= theirTS)
1519                                 {
1520                                         log(DEBUG,"Updating timestamp for %s, our timestamp was %lu and theirs is %lu",c->name,ourTS,theirTS);
1521                                         c->age = theirTS;
1522                                 }
1523                         }
1524                 }
1525                 DoOneToAllButSender(Srv->GetServerName(),"SYNCTS",params,source);
1526                 return true;
1527         }
1528
1529         /* NICK command */
1530         bool IntroduceClient(std::string source, std::deque<std::string> &params)
1531         {
1532                 if (params.size() < 8)
1533                         return true;
1534                 if (params.size() > 8)
1535                 {
1536                         this->WriteLine(":"+Srv->GetServerName()+" KILL "+params[1]+" :Invalid client introduction ("+params[1]+"?)");
1537                         return true;
1538                 }
1539                 // NICK age nick host dhost ident +modes ip :gecos
1540                 //       0    1   2     3     4      5   6     7
1541                 time_t age = atoi(params[0].c_str());
1542                 
1543                 /* This used to have a pretty craq'y loop doing the same thing,
1544                  * now we just let the STL do the hard work (more efficiently)
1545                  */
1546                 params[5] = params[5].substr(params[5].find_first_not_of('+'));
1547                 
1548                 const char* tempnick = params[1].c_str();
1549                 log(DEBUG,"Introduce client %s!%s@%s",tempnick,params[4].c_str(),params[2].c_str());
1550                 
1551                 user_hash::iterator iter = clientlist.find(tempnick);
1552                 
1553                 if (iter != clientlist.end())
1554                 {
1555                         // nick collision
1556                         log(DEBUG,"Nick collision on %s!%s@%s: %lu %lu",tempnick,params[4].c_str(),params[2].c_str(),(unsigned long)age,(unsigned long)iter->second->age);
1557                         this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
1558                         return true;
1559                 }
1560
1561                 clientlist[tempnick] = new userrec();
1562                 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
1563                 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX-1);
1564                 strlcpy(clientlist[tempnick]->host, params[2].c_str(),63);
1565                 strlcpy(clientlist[tempnick]->dhost, params[3].c_str(),63);
1566                 clientlist[tempnick]->server = FindServerNamePtr(source.c_str());
1567                 strlcpy(clientlist[tempnick]->ident, params[4].c_str(),IDENTMAX);
1568                 strlcpy(clientlist[tempnick]->fullname, params[7].c_str(),MAXGECOS);
1569                 clientlist[tempnick]->registered = REG_ALL;
1570                 clientlist[tempnick]->signon = age;
1571                 
1572                 for (std::string::iterator v = params[5].begin(); v != params[5].end(); v++)
1573                 {
1574                         clientlist[tempnick]->modes[(*v)-65] = 1;
1575                 }
1576
1577                 if (params[6].find_first_of(":") != std::string::npos)
1578                         clientlist[tempnick]->SetSockAddr(AF_INET6, params[6].c_str(), 0);
1579                 else
1580                         clientlist[tempnick]->SetSockAddr(AF_INET, params[6].c_str(), 0);
1581
1582                 WriteOpers("*** Client connecting at %s: %s!%s@%s [%s]",clientlist[tempnick]->server,clientlist[tempnick]->nick,clientlist[tempnick]->ident,clientlist[tempnick]->host, clientlist[tempnick]->GetIPString());
1583
1584                 params[7] = ":" + params[7];
1585                 DoOneToAllButSender(source,"NICK",params,source);
1586
1587                 // Increment the Source Servers User Count..
1588                 TreeServer* SourceServer = FindServer(source);
1589                 if (SourceServer)
1590                 {
1591                         log(DEBUG,"Found source server of %s",clientlist[tempnick]->nick);
1592                         SourceServer->AddUserCount();
1593                 }
1594
1595                 return true;
1596         }
1597
1598         /* Send one or more FJOINs for a channel of users.
1599          * If the length of a single line is more than 480-NICKMAX
1600          * in length, it is split over multiple lines.
1601          */
1602         void SendFJoins(TreeServer* Current, chanrec* c)
1603         {
1604                 log(DEBUG,"Sending FJOINs to other server for %s",c->name);
1605                 char list[MAXBUF];
1606                 std::string individual_halfops = ":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age);
1607                 
1608                 size_t dlen, curlen;
1609                 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1610                 int numusers = 0;
1611                 char* ptr = list + dlen;
1612
1613                 CUList *ulist = c->GetUsers();
1614                 std::vector<userrec*> specific_halfop;
1615                 std::vector<userrec*> specific_voice;
1616                 std::string modes = "";
1617                 std::string params = "";
1618
1619                 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1620                 {
1621                         int x = cflags(i->second,c);
1622                         if ((x & UCMODE_HOP) && (x & UCMODE_OP))
1623                         {
1624                                 specific_halfop.push_back(i->second);
1625                         }
1626                         if (((x & UCMODE_HOP) || (x & UCMODE_OP)) && (x & UCMODE_VOICE))
1627                         {
1628                                 specific_voice.push_back(i->second);
1629                         }
1630
1631                         const char* n = "";
1632                         if (x & UCMODE_OP)
1633                         {
1634                                 n = "@";
1635                         }
1636                         else if (x & UCMODE_HOP)
1637                         {
1638                                 n = "%";
1639                         }
1640                         else if (x & UCMODE_VOICE)
1641                         {
1642                                 n = "+";
1643                         }
1644
1645                         size_t ptrlen = snprintf(ptr, MAXBUF, " %s%s", n, i->second->nick);
1646
1647                         curlen += ptrlen;
1648                         ptr += ptrlen;
1649
1650                         numusers++;
1651
1652                         if (curlen > (480-NICKMAX))
1653                         {
1654                                 this->WriteLine(list);
1655                                 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1656                                 ptr = list + dlen;
1657                                 ptrlen = 0;
1658                                 numusers = 0;
1659                                 for (unsigned int y = 0; y < specific_voice.size(); y++)
1660                                 {
1661                                         modes.append("v");
1662                                         params.append(specific_voice[y]->nick).append(" ");
1663                                         //this->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" +v "+specific_voice[y]->nick);
1664                                 }
1665                                 for (unsigned int y = 0; y < specific_halfop.size(); y++)
1666                                 {
1667                                         modes.append("h");
1668                                         params.append(specific_halfop[y]->nick).append(" ");
1669                                         //this->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" +h "+specific_halfop[y]->nick);
1670                                 }
1671                         }
1672                 }
1673                 if (numusers)
1674                 {
1675                         this->WriteLine(list);
1676                         for (unsigned int y = 0; y < specific_voice.size(); y++)
1677                         {
1678                                 modes.append("v");
1679                                 params.append(specific_voice[y]->nick).append(" ");
1680                                 //this->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" +v "+specific_voice[y]->nick);
1681                         }
1682                         for (unsigned int y = 0; y < specific_halfop.size(); y++)
1683                         {
1684                                 modes.append("h");
1685                                 params.append(specific_halfop[y]->nick).append(" ");
1686                                 //this->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" +h "+specific_halfop[y]->nick);
1687                         }
1688                 }
1689                 //std::string modes = "";
1690                 //std::string params = "";
1691                 for (BanList::iterator b = c->bans.begin(); b != c->bans.end(); b++)
1692                 {
1693                         modes.append("b");
1694                         params.append(b->data).append(" ");
1695                 }
1696                 /* XXX: Send each channel mode and its params -- we'll need a method for this in ModeHandler? */
1697                 //FOREACH_MOD(I_OnSyncChannel,OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this));
1698                 this->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" +"+chanmodes(c,true)+modes+" "+params);
1699         }
1700
1701         /* Send G, Q, Z and E lines */
1702         void SendXLines(TreeServer* Current)
1703         {
1704                 char data[MAXBUF];
1705                 std::string n = Srv->GetServerName();
1706                 const char* sn = n.c_str();
1707                 int iterations = 0;
1708                 /* Yes, these arent too nice looking, but they get the job done */
1709                 for (std::vector<ZLine>::iterator i = zlines.begin(); i != zlines.end(); i++, iterations++)
1710                 {
1711                         snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s",sn,i->ipaddr,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1712                         this->WriteLine(data);
1713                 }
1714                 for (std::vector<QLine>::iterator i = qlines.begin(); i != qlines.end(); i++, iterations++)
1715                 {
1716                         snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s",sn,i->nick,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1717                         this->WriteLine(data);
1718                 }
1719                 for (std::vector<GLine>::iterator i = glines.begin(); i != glines.end(); i++, iterations++)
1720                 {
1721                         snprintf(data,MAXBUF,":%s ADDLINE G %s %s %lu %lu :%s",sn,i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1722                         this->WriteLine(data);
1723                 }
1724                 for (std::vector<ELine>::iterator i = elines.begin(); i != elines.end(); i++, iterations++)
1725                 {
1726                         snprintf(data,MAXBUF,":%s ADDLINE E %s %s %lu %lu :%s",sn,i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1727                         this->WriteLine(data);
1728                 }
1729                 for (std::vector<ZLine>::iterator i = pzlines.begin(); i != pzlines.end(); i++, iterations++)
1730                 {
1731                         snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s",sn,i->ipaddr,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1732                         this->WriteLine(data);
1733                 }
1734                 for (std::vector<QLine>::iterator i = pqlines.begin(); i != pqlines.end(); i++, iterations++)
1735                 {
1736                         snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s",sn,i->nick,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1737                         this->WriteLine(data);
1738                 }
1739                 for (std::vector<GLine>::iterator i = pglines.begin(); i != pglines.end(); i++, iterations++)
1740                 {
1741                         snprintf(data,MAXBUF,":%s ADDLINE G %s %s %lu %lu :%s",sn,i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1742                         this->WriteLine(data);
1743                 }
1744                 for (std::vector<ELine>::iterator i = pelines.begin(); i != pelines.end(); i++, iterations++)
1745                 {
1746                         snprintf(data,MAXBUF,":%s ADDLINE E %s %s %lu %lu :%s",sn,i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1747                         this->WriteLine(data);
1748                 }
1749         }
1750
1751         /* Send channel modes and topics */
1752         void SendChannelModes(TreeServer* Current)
1753         {
1754                 char data[MAXBUF];
1755                 std::deque<std::string> list;
1756                 int iterations = 0;
1757                 std::string n = Srv->GetServerName();
1758                 const char* sn = n.c_str();
1759                 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++, iterations++)
1760                 {
1761                         SendFJoins(Current, c->second);
1762                         if (*c->second->topic)
1763                         {
1764                                 snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",sn,c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
1765                                 this->WriteLine(data);
1766                         }
1767                         FOREACH_MOD(I_OnSyncChannel,OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this));
1768                         list.clear();
1769                         c->second->GetExtList(list);
1770                         for (unsigned int j = 0; j < list.size(); j++)
1771                         {
1772                                 FOREACH_MOD(I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
1773                         }
1774                 }
1775         }
1776
1777         /* send all users and their oper state/modes */
1778         void SendUsers(TreeServer* Current)
1779         {
1780                 char data[MAXBUF];
1781                 std::deque<std::string> list;
1782                 int iterations = 0;
1783                 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++, iterations++)
1784                 {
1785                         if (u->second->registered == REG_ALL)
1786                         {
1787                                 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->FormatModes(),u->second->GetIPString(),u->second->fullname);
1788                                 this->WriteLine(data);
1789                                 if (*u->second->oper)
1790                                 {
1791                                         this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
1792                                 }
1793                                 if (*u->second->awaymsg)
1794                                 {
1795                                         this->WriteLine(":"+std::string(u->second->nick)+" AWAY :"+std::string(u->second->awaymsg));
1796                                 }
1797                                 FOREACH_MOD(I_OnSyncUser,OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this));
1798                                 list.clear();
1799                                 u->second->GetExtList(list);
1800                                 for (unsigned int j = 0; j < list.size(); j++)
1801                                 {
1802                                         FOREACH_MOD(I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
1803                                 }
1804                         }
1805                 }
1806         }
1807
1808         /* This function is called when we want to send a netburst to a local
1809          * server. There is a set order we must do this, because for example
1810          * users require their servers to exist, and channels require their
1811          * users to exist. You get the idea.
1812          */
1813         void DoBurst(TreeServer* s)
1814         {
1815                 /* The calls here to ServerInstance-> yield the processing
1816                  * back to the core so that a large burst is split into at least 6 sections
1817                  * (possibly more)
1818                  */
1819                 std::string burst = "BURST "+ConvToStr(time(NULL));
1820                 std::string endburst = "ENDBURST";
1821                 // Because by the end of the netburst, it  could be gone!
1822                 std::string name = s->GetName();
1823                 Srv->SendOpers("*** Bursting to \2"+name+"\2.");
1824                 this->WriteLine(burst);
1825                 /* send our version string */
1826                 this->WriteLine(":"+Srv->GetServerName()+" VERSION :"+Srv->GetVersion());
1827                 /* Send server tree */
1828                 this->SendServers(TreeRoot,s,1);
1829                 /* Send users and their oper status */
1830                 this->SendUsers(s);
1831                 /* Send everything else (channel modes, xlines etc) */
1832                 this->SendChannelModes(s);
1833                 this->SendXLines(s);            
1834                 FOREACH_MOD(I_OnSyncOtherMetaData,OnSyncOtherMetaData((Module*)TreeProtocolModule,(void*)this));
1835                 this->WriteLine(endburst);
1836                 Srv->SendOpers("*** Finished bursting to \2"+name+"\2.");
1837         }
1838
1839         /* This function is called when we receive data from a remote
1840          * server. We buffer the data in a std::string (it doesnt stay
1841          * there for long), reading using InspSocket::Read() which can
1842          * read up to 16 kilobytes in one operation.
1843          *
1844          * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
1845          * THE SOCKET OBJECT FOR US.
1846          */
1847         virtual bool OnDataReady()
1848         {
1849                 char* data = this->Read();
1850                 /* Check that the data read is a valid pointer and it has some content */
1851                 if (data && *data)
1852                 {
1853                         this->in_buffer.append(data);
1854                         /* While there is at least one new line in the buffer,
1855                          * do something useful (we hope!) with it.
1856                          */
1857                         while (in_buffer.find("\n") != std::string::npos)
1858                         {
1859                                 std::string ret = in_buffer.substr(0,in_buffer.find("\n")-1);
1860                                 in_buffer = in_buffer.substr(in_buffer.find("\n")+1,in_buffer.length()-in_buffer.find("\n"));
1861                                 if (ret.find("\r") != std::string::npos)
1862                                         ret = in_buffer.substr(0,in_buffer.find("\r")-1);
1863                                 /* Process this one, abort if it
1864                                  * didnt return true.
1865                                  */
1866                                 if (this->ctx_in)
1867                                 {
1868                                         char out[1024];
1869                                         char result[1024];
1870                                         memset(result,0,1024);
1871                                         memset(out,0,1024);
1872                                         log(DEBUG,"Original string '%s'",ret.c_str());
1873                                         /* ERROR + CAPAB is still allowed unencryped */
1874                                         if ((ret.substr(0,7) != "ERROR :") && (ret.substr(0,6) != "CAPAB "))
1875                                         {
1876                                                 int nbytes = from64tobits(out, ret.c_str(), 1024);
1877                                                 if ((nbytes > 0) && (nbytes < 1024))
1878                                                 {
1879                                                         log(DEBUG,"m_spanningtree: decrypt %d bytes",nbytes);
1880                                                         ctx_in->Decrypt(out, result, nbytes, 0);
1881                                                         for (int t = 0; t < nbytes; t++)
1882                                                                 if (result[t] == '\7') result[t] = 0;
1883                                                         ret = result;
1884                                                 }
1885                                         }
1886                                 }
1887                                 if (!this->ProcessLine(ret))
1888                                 {
1889                                         log(DEBUG,"ProcessLine says no!");
1890                                         return false;
1891                                 }
1892                         }
1893                         return true;
1894                 }
1895                 /* EAGAIN returns an empty but non-NULL string, so this
1896                  * evaluates to TRUE for EAGAIN but to FALSE for EOF.
1897                  */
1898                 return (data && !*data);
1899         }
1900
1901         int WriteLine(std::string line)
1902         {
1903                 log(DEBUG,"OUT: %s",line.c_str());
1904                 if (this->ctx_out)
1905                 {
1906                         char result[10240];
1907                         char result64[10240];
1908                         if (this->keylength)
1909                         {
1910                                 // pad it to the key length
1911                                 int n = this->keylength - (line.length() % this->keylength);
1912                                 if (n)
1913                                 {
1914                                         log(DEBUG,"Append %d chars to line to make it %d long from %d, key length %d",n,n+line.length(),line.length(),this->keylength);
1915                                         line.append(n,'\7');
1916                                 }
1917                         }
1918                         unsigned int ll = line.length();
1919                         ctx_out->Encrypt(line.c_str(), result, ll, 0);
1920                         to64frombits((unsigned char*)result64,(unsigned char*)result,ll);
1921                         line = result64;
1922                         //int from64tobits(char *out, const char *in, int maxlen);
1923                 }
1924                 return this->Write(line + "\r\n");
1925         }
1926
1927         /* Handle ERROR command */
1928         bool Error(std::deque<std::string> &params)
1929         {
1930                 if (params.size() < 1)
1931                         return false;
1932                 WriteOpers("*** ERROR from %s: %s",(InboundServerName != "" ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
1933                 /* we will return false to cause the socket to close. */
1934                 return false;
1935         }
1936
1937         bool Stats(std::string prefix, std::deque<std::string> &params)
1938         {
1939                 /* Get the reply to a STATS query if it matches this servername,
1940                  * and send it back as a load of PUSH queries
1941                  */
1942                 if (params.size() > 1)
1943                 {
1944                         if (Srv->MatchText(Srv->GetServerName(), params[1]))
1945                         {
1946                                 /* It's for our server */
1947                                 string_list results;
1948                                 userrec* source = Srv->FindNick(prefix);
1949                                 if (source)
1950                                 {
1951                                         std::deque<std::string> par;
1952                                         par.push_back(prefix);
1953                                         par.push_back("");
1954                                         DoStats(*(params[0].c_str()), source, results);
1955                                         for (size_t i = 0; i < results.size(); i++)
1956                                         {
1957                                                 par[1] = "::" + results[i];
1958                                                 DoOneToOne(Srv->GetServerName(), "PUSH",par, source->server);
1959                                         }
1960                                 }
1961                         }
1962                         else
1963                         {
1964                                 /* Pass it on */
1965                                 userrec* source = Srv->FindNick(prefix);
1966                                 if (source)
1967                                         DoOneToOne(prefix, "STATS", params, params[1]);
1968                         }
1969                 }
1970                 return true;
1971         }
1972
1973
1974         /* Because the core won't let users or even SERVERS set +o,
1975          * we use the OPERTYPE command to do this.
1976          */
1977         bool OperType(std::string prefix, std::deque<std::string> &params)
1978         {
1979                 if (params.size() != 1)
1980                 {
1981                         log(DEBUG,"Received invalid oper type from %s",prefix.c_str());
1982                         return true;
1983                 }
1984                 std::string opertype = params[0];
1985                 userrec* u = Srv->FindNick(prefix);
1986                 if (u)
1987                 {
1988                         u->modes[UM_OPERATOR] = 1;
1989                         strlcpy(u->oper,opertype.c_str(),NICKMAX-1);
1990                         DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
1991                 }
1992                 return true;
1993         }
1994
1995         /* Because Andy insists that services-compatible servers must
1996          * implement SVSNICK and SVSJOIN, that's exactly what we do :p
1997          */
1998         bool ForceNick(std::string prefix, std::deque<std::string> &params)
1999         {
2000                 if (params.size() < 3)
2001                         return true;
2002
2003                 userrec* u = Srv->FindNick(params[0]);
2004
2005                 if (u)
2006                 {
2007                         DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
2008                         if (IS_LOCAL(u))
2009                         {
2010                                 std::deque<std::string> par;
2011                                 par.push_back(params[1]);
2012                                 /* This is not required as one is sent in OnUserPostNick below
2013                                  */
2014                                 //DoOneToMany(u->nick,"NICK",par);
2015                                 Srv->ChangeUserNick(u,params[1]);
2016                                 u->age = atoi(params[2].c_str());
2017                         }
2018                 }
2019                 return true;
2020         }
2021
2022         bool ServiceJoin(std::string prefix, std::deque<std::string> &params)
2023         {
2024                 if (params.size() < 2)
2025                         return true;
2026
2027                 userrec* u = Srv->FindNick(params[0]);
2028
2029                 if (u)
2030                 {
2031                         Srv->JoinUserToChannel(u,params[1],"");
2032                         DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
2033                 }
2034                 return true;
2035         }
2036
2037         bool RemoteRehash(std::string prefix, std::deque<std::string> &params)
2038         {
2039                 if (params.size() < 1)
2040                         return false;
2041
2042                 std::string servermask = params[0];
2043
2044                 if (Srv->MatchText(Srv->GetServerName(),servermask))
2045                 {
2046                         Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
2047                         Srv->RehashServer();
2048                         ReadConfiguration(false);
2049                 }
2050                 DoOneToAllButSender(prefix,"REHASH",params,prefix);
2051                 return true;
2052         }
2053
2054         bool RemoteKill(std::string prefix, std::deque<std::string> &params)
2055         {
2056                 if (params.size() != 2)
2057                         return true;
2058
2059                 std::string nick = params[0];
2060                 userrec* u = Srv->FindNick(prefix);
2061                 userrec* who = Srv->FindNick(nick);
2062
2063                 if (who)
2064                 {
2065                         /* Prepend kill source, if we don't have one */
2066                         std::string sourceserv = prefix;
2067                         if (u)
2068                         {
2069                                 sourceserv = u->server;
2070                         }
2071                         if (*(params[1].c_str()) != '[')
2072                         {
2073                                 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
2074                         }
2075                         std::string reason = params[1];
2076                         params[1] = ":" + params[1];
2077                         DoOneToAllButSender(prefix,"KILL",params,sourceserv);
2078                         ::Write(who->fd, ":%s KILL %s :%s (%s)", sourceserv.c_str(), who->nick, sourceserv.c_str(), reason.c_str());
2079                         Srv->QuitUser(who,reason);
2080                 }
2081                 return true;
2082         }
2083
2084         bool LocalPong(std::string prefix, std::deque<std::string> &params)
2085         {
2086                 if (params.size() < 1)
2087                         return true;
2088
2089                 if (params.size() == 1)
2090                 {
2091                         TreeServer* ServerSource = FindServer(prefix);
2092                         if (ServerSource)
2093                         {
2094                                 ServerSource->SetPingFlag();
2095                         }
2096                 }
2097                 else
2098                 {
2099                         std::string forwardto = params[1];
2100                         if (forwardto == Srv->GetServerName())
2101                         {
2102                                 /*
2103                                  * this is a PONG for us
2104                                  * if the prefix is a user, check theyre local, and if they are,
2105                                  * dump the PONG reply back to their fd. If its a server, do nowt.
2106                                  * Services might want to send these s->s, but we dont need to yet.
2107                                  */
2108                                 userrec* u = Srv->FindNick(prefix);
2109
2110                                 if (u)
2111                                 {
2112                                         WriteServ(u->fd,"PONG %s %s",params[0].c_str(),params[1].c_str());
2113                                 }
2114                         }
2115                         else
2116                         {
2117                                 // not for us, pass it on :)
2118                                 DoOneToOne(prefix,"PONG",params,forwardto);
2119                         }
2120                 }
2121
2122                 return true;
2123         }
2124         
2125         bool MetaData(std::string prefix, std::deque<std::string> &params)
2126         {
2127                 if (params.size() < 3)
2128                         return true;
2129
2130                 TreeServer* ServerSource = FindServer(prefix);
2131
2132                 if (ServerSource)
2133                 {
2134                         if (params[0] == "*")
2135                         {
2136                                 FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
2137                         }
2138                         else if (*(params[0].c_str()) == '#')
2139                         {
2140                                 chanrec* c = Srv->FindChannel(params[0]);
2141                                 if (c)
2142                                 {
2143                                         FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
2144                                 }
2145                         }
2146                         else if (*(params[0].c_str()) != '#')
2147                         {
2148                                 userrec* u = Srv->FindNick(params[0]);
2149                                 if (u)
2150                                 {
2151                                         FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
2152                                 }
2153                         }
2154                 }
2155
2156                 params[2] = ":" + params[2];
2157                 DoOneToAllButSender(prefix,"METADATA",params,prefix);
2158                 return true;
2159         }
2160
2161         bool ServerVersion(std::string prefix, std::deque<std::string> &params)
2162         {
2163                 if (params.size() < 1)
2164                         return true;
2165
2166                 TreeServer* ServerSource = FindServer(prefix);
2167
2168                 if (ServerSource)
2169                 {
2170                         ServerSource->SetVersion(params[0]);
2171                 }
2172                 params[0] = ":" + params[0];
2173                 DoOneToAllButSender(prefix,"VERSION",params,prefix);
2174                 return true;
2175         }
2176
2177         bool ChangeHost(std::string prefix, std::deque<std::string> &params)
2178         {
2179                 if (params.size() < 1)
2180                         return true;
2181
2182                 userrec* u = Srv->FindNick(prefix);
2183
2184                 if (u)
2185                 {
2186                         Srv->ChangeHost(u,params[0]);
2187                         DoOneToAllButSender(prefix,"FHOST",params,u->server);
2188                 }
2189                 return true;
2190         }
2191
2192         bool AddLine(std::string prefix, std::deque<std::string> &params)
2193         {
2194                 if (params.size() < 6)
2195                         return true;
2196
2197                 bool propogate = false;
2198
2199                 switch (*(params[0].c_str()))
2200                 {
2201                         case 'Z':
2202                                 propogate = add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2203                                 zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2204                         break;
2205                         case 'Q':
2206                                 propogate = add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2207                                 qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2208                         break;
2209                         case 'E':
2210                                 propogate = add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2211                                 eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2212                         break;
2213                         case 'G':
2214                                 propogate = add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2215                                 gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2216                         break;
2217                         case 'K':
2218                                 propogate = add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2219                         break;
2220                         default:
2221                                 /* Just in case... */
2222                                 Srv->SendOpers("*** \2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");
2223                                 propogate = false;
2224                         break;
2225                 }
2226
2227                 /* Send it on its way */
2228                 if (propogate)
2229                 {
2230                         if (atoi(params[4].c_str()))
2231                         {
2232                                 WriteOpers("*** %s Added %cLINE on %s to expire in %lu seconds (%s).",prefix.c_str(),*(params[0].c_str()),params[1].c_str(),atoi(params[4].c_str()),params[5].c_str());
2233                         }
2234                         else
2235                         {
2236                                 WriteOpers("*** %s Added permenant %cLINE on %s (%s).",prefix.c_str(),*(params[0].c_str()),params[1].c_str(),params[5].c_str());
2237                         }
2238                         params[5] = ":" + params[5];
2239                         DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
2240                 }
2241                 if (!this->bursting)
2242                 {
2243                         log(DEBUG,"Applying lines...");
2244                         apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2245                 }
2246                 return true;
2247         }
2248
2249         bool ChangeName(std::string prefix, std::deque<std::string> &params)
2250         {
2251                 if (params.size() < 1)
2252                         return true;
2253
2254                 userrec* u = Srv->FindNick(prefix);
2255
2256                 if (u)
2257                 {
2258                         Srv->ChangeGECOS(u,params[0]);
2259                         params[0] = ":" + params[0];
2260                         DoOneToAllButSender(prefix,"FNAME",params,u->server);
2261                 }
2262                 return true;
2263         }
2264
2265         bool Whois(std::string prefix, std::deque<std::string> &params)
2266         {
2267                 if (params.size() < 1)
2268                         return true;
2269
2270                 log(DEBUG,"In IDLE command");
2271                 userrec* u = Srv->FindNick(prefix);
2272
2273                 if (u)
2274                 {
2275                         log(DEBUG,"USER EXISTS: %s",u->nick);
2276                         // an incoming request
2277                         if (params.size() == 1)
2278                         {
2279                                 userrec* x = Srv->FindNick(params[0]);
2280                                 if ((x) && (IS_LOCAL(x)))
2281                                 {
2282                                         userrec* x = Srv->FindNick(params[0]);
2283                                         log(DEBUG,"Got IDLE");
2284                                         char signon[MAXBUF];
2285                                         char idle[MAXBUF];
2286                                         log(DEBUG,"Sending back IDLE 3");
2287                                         snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
2288                                         snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-time(NULL)));
2289                                         std::deque<std::string> par;
2290                                         par.push_back(prefix);
2291                                         par.push_back(signon);
2292                                         par.push_back(idle);
2293                                         // ours, we're done, pass it BACK
2294                                         DoOneToOne(params[0],"IDLE",par,u->server);
2295                                 }
2296                                 else
2297                                 {
2298                                         // not ours pass it on
2299                                         DoOneToOne(prefix,"IDLE",params,x->server);
2300                                 }
2301                         }
2302                         else if (params.size() == 3)
2303                         {
2304                                 std::string who_did_the_whois = params[0];
2305                                 userrec* who_to_send_to = Srv->FindNick(who_did_the_whois);
2306                                 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2307                                 {
2308                                         log(DEBUG,"Got final IDLE");
2309                                         // an incoming reply to a whois we sent out
2310                                         std::string nick_whoised = prefix;
2311                                         unsigned long signon = atoi(params[1].c_str());
2312                                         unsigned long idle = atoi(params[2].c_str());
2313                                         if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2314                                                 do_whois(who_to_send_to,u,signon,idle,nick_whoised.c_str());
2315                                 }
2316                                 else
2317                                 {
2318                                         // not ours, pass it on
2319                                         DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
2320                                 }
2321                         }
2322                 }
2323                 return true;
2324         }
2325
2326         bool Push(std::string prefix, std::deque<std::string> &params)
2327         {
2328                 if (params.size() < 2)
2329                         return true;
2330
2331                 userrec* u = Srv->FindNick(params[0]);
2332
2333                 if (!u)
2334                         return true;
2335
2336                 if (IS_LOCAL(u))
2337                 {
2338                         ::Write(u->fd,"%s",params[1].c_str());
2339                 }
2340                 else
2341                 {
2342                         // continue the raw onwards
2343                         params[1] = ":" + params[1];
2344                         DoOneToOne(prefix,"PUSH",params,u->server);
2345                 }
2346                 return true;
2347         }
2348
2349         bool Time(std::string prefix, std::deque<std::string> &params)
2350         {
2351                 // :source.server TIME remote.server sendernick
2352                 // :remote.server TIME source.server sendernick TS
2353                 if (params.size() == 2)
2354                 {
2355                         // someone querying our time?
2356                         if (Srv->GetServerName() == params[0])
2357                         {
2358                                 userrec* u = Srv->FindNick(params[1]);
2359                                 if (u)
2360                                 {
2361                                         char curtime[256];
2362                                         snprintf(curtime,256,"%lu",(unsigned long)time(NULL));
2363                                         params.push_back(curtime);
2364                                         params[0] = prefix;
2365                                         DoOneToOne(Srv->GetServerName(),"TIME",params,params[0]);
2366                                 }
2367                         }
2368                         else
2369                         {
2370                                 // not us, pass it on
2371                                 userrec* u = Srv->FindNick(params[1]);
2372                                 if (u)
2373                                         DoOneToOne(prefix,"TIME",params,params[0]);
2374                         }
2375                 }
2376                 else if (params.size() == 3)
2377                 {
2378                         // a response to a previous TIME
2379                         userrec* u = Srv->FindNick(params[1]);
2380                         if ((u) && (IS_LOCAL(u)))
2381                         {
2382                         time_t rawtime = atol(params[2].c_str());
2383                         struct tm * timeinfo;
2384                         timeinfo = localtime(&rawtime);
2385                                 char tms[26];
2386                                 snprintf(tms,26,"%s",asctime(timeinfo));
2387                                 tms[24] = 0;
2388                         WriteServ(u->fd,"391 %s %s :%s",u->nick,prefix.c_str(),tms);
2389                         }
2390                         else
2391                         {
2392                                 if (u)
2393                                         DoOneToOne(prefix,"TIME",params,u->server);
2394                         }
2395                 }
2396                 return true;
2397         }
2398         
2399         bool LocalPing(std::string prefix, std::deque<std::string> &params)
2400         {
2401                 if (params.size() < 1)
2402                         return true;
2403
2404                 if (params.size() == 1)
2405                 {
2406                         std::string stufftobounce = params[0];
2407                         this->WriteLine(":"+Srv->GetServerName()+" PONG "+stufftobounce);
2408                         return true;
2409                 }
2410                 else
2411                 {
2412                         std::string forwardto = params[1];
2413                         if (forwardto == Srv->GetServerName())
2414                         {
2415                                 // this is a ping for us, send back PONG to the requesting server
2416                                 params[1] = params[0];
2417                                 params[0] = forwardto;
2418                                 DoOneToOne(forwardto,"PONG",params,params[1]);
2419                         }
2420                         else
2421                         {
2422                                 // not for us, pass it on :)
2423                                 DoOneToOne(prefix,"PING",params,forwardto);
2424                         }
2425                         return true;
2426                 }
2427         }
2428
2429         bool RemoteServer(std::string prefix, std::deque<std::string> &params)
2430         {
2431                 if (params.size() < 4)
2432                         return false;
2433
2434                 std::string servername = params[0];
2435                 std::string password = params[1];
2436                 // hopcount is not used for a remote server, we calculate this ourselves
2437                 std::string description = params[3];
2438                 TreeServer* ParentOfThis = FindServer(prefix);
2439
2440                 if (!ParentOfThis)
2441                 {
2442                         this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
2443                         return false;
2444                 }
2445                 TreeServer* CheckDupe = FindServer(servername);
2446                 if (CheckDupe)
2447                 {
2448                         this->WriteLine("ERROR :Server "+servername+" already exists!");
2449                         Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists");
2450                         return false;
2451                 }
2452                 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
2453                 ParentOfThis->AddChild(Node);
2454                 params[3] = ":" + params[3];
2455                 DoOneToAllButSender(prefix,"SERVER",params,prefix);
2456                 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
2457                 return true;
2458         }
2459
2460         bool Outbound_Reply_Server(std::deque<std::string> &params)
2461         {
2462                 if (params.size() < 4)
2463                         return false;
2464
2465                 irc::string servername = params[0].c_str();
2466                 std::string sname = params[0];
2467                 std::string password = params[1];
2468                 int hops = atoi(params[2].c_str());
2469
2470                 if (hops)
2471                 {
2472                         this->WriteLine("ERROR :Server too far away for authentication");
2473                         Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2474                         return false;
2475                 }
2476                 std::string description = params[3];
2477                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2478                 {
2479                         if ((x->Name == servername) && (x->RecvPass == password))
2480                         {
2481                                 TreeServer* CheckDupe = FindServer(sname);
2482                                 if (CheckDupe)
2483                                 {
2484                                         this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
2485                                         Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
2486                                         return false;
2487                                 }
2488                                 // Begin the sync here. this kickstarts the
2489                                 // other side, waiting in WAIT_AUTH_2 state,
2490                                 // into starting their burst, as it shows
2491                                 // that we're happy.
2492                                 this->LinkState = CONNECTED;
2493                                 // we should add the details of this server now
2494                                 // to the servers tree, as a child of the root
2495                                 // node.
2496                                 TreeServer* Node = new TreeServer(sname,description,TreeRoot,this);
2497                                 TreeRoot->AddChild(Node);
2498                                 params[3] = ":" + params[3];
2499                                 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,sname);
2500                                 this->bursting = true;
2501                                 this->DoBurst(Node);
2502                                 return true;
2503                         }
2504                 }
2505                 this->WriteLine("ERROR :Invalid credentials");
2506                 Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, invalid link credentials");
2507                 return false;
2508         }
2509
2510         bool Inbound_Server(std::deque<std::string> &params)
2511         {
2512                 if (params.size() < 4)
2513                         return false;
2514
2515                 irc::string servername = params[0].c_str();
2516                 std::string sname = params[0];
2517                 std::string password = params[1];
2518                 int hops = atoi(params[2].c_str());
2519
2520                 if (hops)
2521                 {
2522                         this->WriteLine("ERROR :Server too far away for authentication");
2523                         Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2524                         return false;
2525                 }
2526                 std::string description = params[3];
2527                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2528                 {
2529                         if ((x->Name == servername) && (x->RecvPass == password))
2530                         {
2531                                 TreeServer* CheckDupe = FindServer(sname);
2532                                 if (CheckDupe)
2533                                 {
2534                                         this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
2535                                         Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
2536                                         return false;
2537                                 }
2538                                 /* If the config says this link is encrypted, but the remote side
2539                                  * hasnt bothered to send the AES command before SERVER, then we
2540                                  * boot them off as we MUST have this connection encrypted.
2541                                  */
2542                                 if ((x->EncryptionKey != "") && (!this->ctx_in))
2543                                 {
2544                                         this->WriteLine("ERROR :This link requires AES encryption to be enabled. Plaintext connection refused.");
2545                                         Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, remote server did not enable AES.");
2546                                         return false;
2547                                 }
2548                                 Srv->SendOpers("*** Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
2549                                 this->InboundServerName = sname;
2550                                 this->InboundDescription = description;
2551                                 // this is good. Send our details: Our server name and description and hopcount of 0,
2552                                 // along with the sendpass from this block.
2553                                 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
2554                                 // move to the next state, we are now waiting for THEM.
2555                                 this->LinkState = WAIT_AUTH_2;
2556                                 return true;
2557                         }
2558                 }
2559                 this->WriteLine("ERROR :Invalid credentials");
2560                 Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, invalid link credentials");
2561                 return false;
2562         }
2563
2564         void Split(std::string line, std::deque<std::string> &n)
2565         {
2566                 n.clear();
2567                 irc::tokenstream tokens(line);
2568                 std::string param;
2569                 while ((param = tokens.GetToken()) != "")
2570                         n.push_back(param);
2571                 return;
2572         }
2573
2574         bool ProcessLine(std::string line)
2575         {
2576                 std::deque<std::string> params;
2577                 irc::string command;
2578                 std::string prefix;
2579                 
2580                 if (line.empty())
2581                         return true;
2582                 
2583                 line = line.substr(0, line.find_first_of("\r\n"));
2584                 
2585                 log(DEBUG,"IN: %s", line.c_str());
2586                 
2587                 this->Split(line.c_str(),params);
2588                         
2589                 if ((params[0][0] == ':') && (params.size() > 1))
2590                 {
2591                         prefix = params[0].substr(1);
2592                         params.pop_front();
2593                 }
2594
2595                 command = params[0].c_str();
2596                 params.pop_front();
2597
2598                 if ((!this->ctx_in) && (command == "AES"))
2599                 {
2600                         std::string sserv = params[0];
2601                         for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2602                         {
2603                                 if ((x->EncryptionKey != "") && (x->Name == sserv))
2604                                 {
2605                                         this->InitAES(x->EncryptionKey,sserv);
2606                                 }
2607                         }
2608
2609                         return true;
2610                 }
2611                 else if ((this->ctx_in) && (command == "AES"))
2612                 {
2613                         WriteOpers("*** \2AES\2: Encryption already enabled on this connection yet %s is trying to enable it twice!",params[0].c_str());
2614                 }
2615
2616                 switch (this->LinkState)
2617                 {
2618                         TreeServer* Node;
2619                         
2620                         case WAIT_AUTH_1:
2621                                 // Waiting for SERVER command from remote server. Server initiating
2622                                 // the connection sends the first SERVER command, listening server
2623                                 // replies with theirs if its happy, then if the initiator is happy,
2624                                 // it starts to send its net sync, which starts the merge, otherwise
2625                                 // it sends an ERROR.
2626                                 if (command == "PASS")
2627                                 {
2628                                         /* Silently ignored */
2629                                 }
2630                                 else if (command == "SERVER")
2631                                 {
2632                                         return this->Inbound_Server(params);
2633                                 }
2634                                 else if (command == "ERROR")
2635                                 {
2636                                         return this->Error(params);
2637                                 }
2638                                 else if (command == "USER")
2639                                 {
2640                                         this->WriteLine("ERROR :Client connections to this port are prohibited.");
2641                                         return false;
2642                                 }
2643                                 else if (command == "CAPAB")
2644                                 {
2645                                         return this->Capab(params);
2646                                 }
2647                                 else if ((command == "U") || (command == "S"))
2648                                 {
2649                                         this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
2650                                         return false;
2651                                 }
2652                                 else
2653                                 {
2654                                         this->WriteLine("ERROR :Invalid command in negotiation phase.");
2655                                         return false;
2656                                 }
2657                         break;
2658                         case WAIT_AUTH_2:
2659                                 // Waiting for start of other side's netmerge to say they liked our
2660                                 // password.
2661                                 if (command == "SERVER")
2662                                 {
2663                                         // cant do this, they sent it to us in the WAIT_AUTH_1 state!
2664                                         // silently ignore.
2665                                         return true;
2666                                 }
2667                                 else if ((command == "U") || (command == "S"))
2668                                 {
2669                                         this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
2670                                         return false;
2671                                 }
2672                                 else if (command == "BURST")
2673                                 {
2674                                         if (params.size())
2675                                         {
2676                                                 /* If a time stamp is provided, try and check syncronization */
2677                                                 time_t THEM = atoi(params[0].c_str());
2678                                                 long delta = THEM-time(NULL);
2679                                                 if ((delta < -600) || (delta > 600))
2680                                                 {
2681                                                         WriteOpers("*** \2ERROR\2: Your clocks are out by %d seconds (this is more than ten minutes). Link aborted, \2PLEASE SYNC YOUR CLOCKS!\2",abs(delta));
2682                                                         this->WriteLine("ERROR :Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than ten minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
2683                                                         return false;
2684                                                 }
2685                                                 else if ((delta < -60) || (delta > 60))
2686                                                 {
2687                                                         WriteOpers("*** \2WARNING\2: Your clocks are out by %d seconds, please consider synching your clocks.",abs(delta));
2688                                                 }
2689                                         }
2690                                         this->LinkState = CONNECTED;
2691                                         Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
2692                                         TreeRoot->AddChild(Node);
2693                                         params.clear();
2694                                         params.push_back(InboundServerName);
2695                                         params.push_back("*");
2696                                         params.push_back("1");
2697                                         params.push_back(":"+InboundDescription);
2698                                         DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
2699                                         this->bursting = true;
2700                                         this->DoBurst(Node);
2701                                 }
2702                                 else if (command == "ERROR")
2703                                 {
2704                                         return this->Error(params);
2705                                 }
2706                                 else if (command == "CAPAB")
2707                                 {
2708                                         return this->Capab(params);
2709                                 }
2710                                 
2711                         break;
2712                         case LISTENER:
2713                                 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
2714                                 return false;
2715                         break;
2716                         case CONNECTING:
2717                                 if (command == "SERVER")
2718                                 {
2719                                         // another server we connected to, which was in WAIT_AUTH_1 state,
2720                                         // has just sent us their credentials. If we get this far, theyre
2721                                         // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
2722                                         // if we're happy with this, we should send our netburst which
2723                                         // kickstarts the merge.
2724                                         return this->Outbound_Reply_Server(params);
2725                                 }
2726                                 else if (command == "ERROR")
2727                                 {
2728                                         return this->Error(params);
2729                                 }
2730                         break;
2731                         case CONNECTED:
2732                                 // This is the 'authenticated' state, when all passwords
2733                                 // have been exchanged and anything past this point is taken
2734                                 // as gospel.
2735                                 
2736                                 if (prefix != "")
2737                                 {
2738                                         std::string direction = prefix;
2739                                         userrec* t = Srv->FindNick(prefix);
2740                                         if (t)
2741                                         {
2742                                                 direction = t->server;
2743                                         }
2744                                         TreeServer* route_back_again = BestRouteTo(direction);
2745                                         if ((!route_back_again) || (route_back_again->GetSocket() != this))
2746                                         {
2747                                                 if (route_back_again)
2748                                                         log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
2749                                                 return true;
2750                                         }
2751
2752                                         /* Fix by brain:
2753                                          * When there is activity on the socket, reset the ping counter so
2754                                          * that we're not wasting bandwidth pinging an active server.
2755                                          */ 
2756                                         route_back_again->SetNextPingTime(time(NULL) + 120);
2757                                         route_back_again->SetPingFlag();
2758                                 }
2759                                 
2760                                 if (command == "SVSMODE")
2761                                 {
2762                                         /* Services expects us to implement
2763                                          * SVSMODE. In inspircd its the same as
2764                                          * MODE anyway.
2765                                          */
2766                                         command = "MODE";
2767                                 }
2768                                 std::string target = "";
2769                                 /* Yes, know, this is a mess. Its reasonably fast though as we're
2770                                  * working with std::string here.
2771                                  */
2772                                 if ((command == "NICK") && (params.size() > 1))
2773                                 {
2774                                         return this->IntroduceClient(prefix,params);
2775                                 }
2776                                 else if (command == "FJOIN")
2777                                 {
2778                                         return this->ForceJoin(prefix,params);
2779                                 }
2780                                 else if (command == "STATS")
2781                                 {
2782                                         return this->Stats(prefix, params);
2783                                 }
2784                                 else if (command == "SERVER")
2785                                 {
2786                                         return this->RemoteServer(prefix,params);
2787                                 }
2788                                 else if (command == "ERROR")
2789                                 {
2790                                         return this->Error(params);
2791                                 }
2792                                 else if (command == "OPERTYPE")
2793                                 {
2794                                         return this->OperType(prefix,params);
2795                                 }
2796                                 else if (command == "FMODE")
2797                                 {
2798                                         return this->ForceMode(prefix,params);
2799                                 }
2800                                 else if (command == "KILL")
2801                                 {
2802                                         return this->RemoteKill(prefix,params);
2803                                 }
2804                                 else if (command == "FTOPIC")
2805                                 {
2806                                         return this->ForceTopic(prefix,params);
2807                                 }
2808                                 else if (command == "REHASH")
2809                                 {
2810                                         return this->RemoteRehash(prefix,params);
2811                                 }
2812                                 else if (command == "METADATA")
2813                                 {
2814                                         return this->MetaData(prefix,params);
2815                                 }
2816                                 else if (command == "PING")
2817                                 {
2818                                         /*
2819                                          * We just got a ping from a server that's bursting.
2820                                          * This can't be right, so set them to not bursting, and
2821                                          * apply their lines.
2822                                          */
2823                                         if (this->bursting)
2824                                         {
2825                                                 this->bursting = false;
2826                                                 apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2827                                         }
2828                                         if (prefix == "")
2829                                         {
2830                                                 prefix = this->GetName();
2831                                         }
2832                                         return this->LocalPing(prefix,params);
2833                                 }
2834                                 else if (command == "PONG")
2835                                 {
2836                                         /*
2837                                          * We just got a pong from a server that's bursting.
2838                                          * This can't be right, so set them to not bursting, and
2839                                          * apply their lines.
2840                                          */
2841                                         if (this->bursting)
2842                                         {
2843                                                 this->bursting = false;
2844                                                 apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2845                                         }
2846                                         if (prefix == "")
2847                                         {
2848                                                 prefix = this->GetName();
2849                                         }
2850                                         return this->LocalPong(prefix,params);
2851                                 }
2852                                 else if (command == "VERSION")
2853                                 {
2854                                         return this->ServerVersion(prefix,params);
2855                                 }
2856                                 else if (command == "FHOST")
2857                                 {
2858                                         return this->ChangeHost(prefix,params);
2859                                 }
2860                                 else if (command == "FNAME")
2861                                 {
2862                                         return this->ChangeName(prefix,params);
2863                                 }
2864                                 else if (command == "ADDLINE")
2865                                 {
2866                                         return this->AddLine(prefix,params);
2867                                 }
2868                                 else if (command == "SVSNICK")
2869                                 {
2870                                         if (prefix == "")
2871                                         {
2872                                                 prefix = this->GetName();
2873                                         }
2874                                         return this->ForceNick(prefix,params);
2875                                 }
2876                                 else if (command == "IDLE")
2877                                 {
2878                                         return this->Whois(prefix,params);
2879                                 }
2880                                 else if (command == "PUSH")
2881                                 {
2882                                         return this->Push(prefix,params);
2883                                 }
2884                                 else if (command == "TIME")
2885                                 {
2886                                         return this->Time(prefix,params);
2887                                 }
2888                                 else if ((command == "KICK") && (IsServer(prefix)))
2889                                 {
2890                                         std::string sourceserv = this->myhost;
2891                                         if (params.size() == 3)
2892                                         {
2893                                                 userrec* user = Srv->FindNick(params[1]);
2894                                                 chanrec* chan = Srv->FindChannel(params[0]);
2895                                                 if (user && chan)
2896                                                 {
2897                                                         server_kick_channel(user,chan,(char*)params[2].c_str(),false);
2898                                                 }
2899                                         }
2900                                         if (this->InboundServerName != "")
2901                                         {
2902                                                 sourceserv = this->InboundServerName;
2903                                         }
2904                                         return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
2905                                 }
2906                                 else if (command == "SVSJOIN")
2907                                 {
2908                                         if (prefix == "")
2909                                         {
2910                                                 prefix = this->GetName();
2911                                         }
2912                                         return this->ServiceJoin(prefix,params);
2913                                 }
2914                                 else if (command == "SQUIT")
2915                                 {
2916                                         if (params.size() == 2)
2917                                         {
2918                                                 this->Squit(FindServer(params[0]),params[1]);
2919                                         }
2920                                         return true;
2921                                 }
2922                                 else if (command == "ENDBURST")
2923                                 {
2924                                         this->bursting = false;
2925                                         apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2926                                         std::string sourceserv = this->myhost;
2927                                         if (this->InboundServerName != "")
2928                                         {
2929                                                 sourceserv = this->InboundServerName;
2930                                         }
2931                                         WriteOpers("*** Received end of netburst from \2%s\2",sourceserv.c_str());
2932                                         return true;
2933                                 }
2934                                 else
2935                                 {
2936                                         // not a special inter-server command.
2937                                         // Emulate the actual user doing the command,
2938                                         // this saves us having a huge ugly parser.
2939                                         userrec* who = Srv->FindNick(prefix);
2940                                         std::string sourceserv = this->myhost;
2941                                         if (this->InboundServerName != "")
2942                                         {
2943                                                 sourceserv = this->InboundServerName;
2944                                         }
2945                                         if (who)
2946                                         {
2947                                                 if ((command == "NICK") && (params.size() > 0))
2948                                                 {
2949                                                         /* On nick messages, check that the nick doesnt
2950                                                          * already exist here. If it does, kill their copy,
2951                                                          * and our copy.
2952                                                          */
2953                                                         userrec* x = Srv->FindNick(params[0]);
2954                                                         if ((x) && (x != who))
2955                                                         {
2956                                                                 std::deque<std::string> p;
2957                                                                 p.push_back(params[0]);
2958                                                                 p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
2959                                                                 DoOneToMany(Srv->GetServerName(),"KILL",p);
2960                                                                 p.clear();
2961                                                                 p.push_back(prefix);
2962                                                                 p.push_back("Nickname collision");
2963                                                                 DoOneToMany(Srv->GetServerName(),"KILL",p);
2964                                                                 Srv->QuitUser(x,"Nickname collision ("+prefix+" -> "+params[0]+")");
2965                                                                 userrec* y = Srv->FindNick(prefix);
2966                                                                 if (y)
2967                                                                 {
2968                                                                         Srv->QuitUser(y,"Nickname collision");
2969                                                                 }
2970                                                                 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
2971                                                         }
2972                                                 }
2973                                                 // its a user
2974                                                 target = who->server;
2975                                                 const char* strparams[127];
2976                                                 for (unsigned int q = 0; q < params.size(); q++)
2977                                                 {
2978                                                         strparams[q] = params[q].c_str();
2979                                                 }
2980                                                 if (!Srv->CallCommandHandler(command.c_str(), strparams, params.size(), who))
2981                                                 {
2982                                                         this->WriteLine("ERROR :Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
2983                                                         return false;
2984                                                 }
2985                                         }
2986                                         else
2987                                         {
2988                                                 // its not a user. Its either a server, or somethings screwed up.
2989                                                 if (IsServer(prefix))
2990                                                 {
2991                                                         target = Srv->GetServerName();
2992                                                 }
2993                                                 else
2994                                                 {
2995                                                         log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
2996                                                         return true;
2997                                                 }
2998                                         }
2999                                         return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3000
3001                                 }
3002                                 return true;
3003                         break;
3004                 }
3005                 return true;
3006         }
3007
3008         virtual std::string GetName()
3009         {
3010                 std::string sourceserv = this->myhost;
3011                 if (this->InboundServerName != "")
3012                 {
3013                         sourceserv = this->InboundServerName;
3014                 }
3015                 return sourceserv;
3016         }
3017
3018         virtual void OnTimeout()
3019         {
3020                 if (this->LinkState == CONNECTING)
3021                 {
3022                         Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
3023                 }
3024         }
3025
3026         virtual void OnClose()
3027         {
3028                 // Connection closed.
3029                 // If the connection is fully up (state CONNECTED)
3030                 // then propogate a netsplit to all peers.
3031                 std::string quitserver = this->myhost;
3032                 if (this->InboundServerName != "")
3033                 {
3034                         quitserver = this->InboundServerName;
3035                 }
3036                 TreeServer* s = FindServer(quitserver);
3037                 if (s)
3038                 {
3039                         Squit(s,"Remote host closed the connection");
3040                 }
3041                 WriteOpers("Server '\2%s\2' closed the connection.",quitserver.c_str());
3042         }
3043
3044         virtual int OnIncomingConnection(int newsock, char* ip)
3045         {
3046                 /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
3047                  * or discovering if this port is the server port, we don't allow connections from any
3048                  * IPs for which we don't have a link block.
3049                  */
3050                 bool found = false;
3051                 vector<Link>::iterator i;
3052                 found = (std::find(ValidIPs.begin(), ValidIPs.end(), ip) != ValidIPs.end());
3053                 if (!found)
3054                 {
3055                         WriteOpers("Server connection from %s denied (no link blocks with that IP address)", ip);
3056                         close(newsock);
3057                         return false;
3058                 }
3059                 TreeSocket* s = new TreeSocket(newsock, ip);
3060                 Srv->AddSocket(s);
3061                 return true;
3062         }
3063 };
3064
3065 /** This class is used to resolve server hostnames during /connect and autoconnect.
3066  * As of 1.1, the resolver system is seperated out from InspSocket, so we must do this
3067  * resolver step first ourselves if we need it. This is totally nonblocking, and will
3068  * callback to OnLookupComplete or OnError when completed. Once it has completed we
3069  * will have an IP address which we can then use to continue our connection.
3070  */
3071 class ServernameResolver : public Resolver
3072 {       
3073  private:
3074         /** A copy of the Link tag info for what we're connecting to.
3075          * We take a copy, rather than using a pointer, just in case the
3076          * admin takes the tag away and rehashes while the domain is resolving.
3077          */
3078         Link MyLink;
3079  public:        
3080         ServernameResolver(const std::string &hostname, Link x) : Resolver(hostname, DNS_QUERY_FORWARD), MyLink(x)
3081         {
3082                 /* Nothing in here, folks */
3083         }
3084         
3085         void OnLookupComplete(const std::string &result)
3086         {
3087                 /* Initiate the connection, now that we have an IP to use.
3088                  * Passing a hostname directly to InspSocket causes it to
3089                  * just bail and set its FD to -1.
3090                  */
3091                 TreeServer* CheckDupe = FindServer(MyLink.Name.c_str());
3092                 if (!CheckDupe) /* Check that nobody tried to connect it successfully while we were resolving */
3093                 {
3094                         TreeSocket* newsocket = new TreeSocket(result,MyLink.Port,false,10,MyLink.Name.c_str());
3095                         if (newsocket->GetFd() > -1)
3096                         {
3097                                 /* We're all OK */
3098                                 Srv->AddSocket(newsocket);
3099                         }
3100                         else
3101                         {
3102                                 /* Something barfed, show the opers */
3103                                 WriteOpers("*** CONNECT: Error connecting \002%s\002: %s.",MyLink.Name.c_str(),strerror(errno));
3104                                 delete newsocket;
3105                         }
3106                 }
3107         }
3108
3109         void OnError(ResolverError e, const std::string &errormessage)
3110         {
3111                 /* Ooops! */
3112                 WriteOpers("*** CONNECT: Error connecting \002%s\002: Unable to resolve hostname - %s",MyLink.Name.c_str(),errormessage.c_str());
3113         }
3114 };
3115
3116 class SecurityIPResolver : public Resolver
3117 {
3118  private:
3119         Link MyLink;
3120  public:
3121         SecurityIPResolver(const std::string &hostname, Link x) : Resolver(hostname, DNS_QUERY_FORWARD), MyLink(x)
3122         {
3123         }
3124
3125         void OnLookupComplete(const std::string &result)
3126         {
3127                 log(DEBUG,"Security IP cache: Adding IP address '%s' for Link '%s'",result.c_str(),MyLink.Name.c_str());
3128                 ValidIPs.push_back(result);
3129         }
3130
3131         void OnError(ResolverError e, const std::string &errormessage)
3132         {
3133                 log(DEBUG,"Could not resolve IP associated with Link '%s': %s",MyLink.Name.c_str(),errormessage.c_str());
3134         }
3135 };
3136
3137 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
3138 {
3139         for (unsigned int c = 0; c < list.size(); c++)
3140         {
3141                 if (list[c] == server)
3142                 {
3143                         return;
3144                 }
3145         }
3146         list.push_back(server);
3147 }
3148
3149 // returns a list of DIRECT servernames for a specific channel
3150 void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
3151 {
3152         CUList *ulist = c->GetUsers();
3153         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
3154         {
3155                 if (i->second->fd < 0)
3156                 {
3157                         TreeServer* best = BestRouteTo(i->second->server);
3158                         if (best)
3159                                 AddThisServer(best,list);
3160                 }
3161         }
3162         return;
3163 }
3164
3165 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, irc::string command, std::deque<std::string> &params)
3166 {
3167         TreeServer* omitroute = BestRouteTo(omit);
3168         if ((command == "NOTICE") || (command == "PRIVMSG"))
3169         {
3170                 if (params.size() >= 2)
3171                 {
3172                         /* Prefixes */
3173                         if ((*(params[0].c_str()) == '@') || (*(params[0].c_str()) == '%') || (*(params[0].c_str()) == '+'))
3174                         {
3175                                 params[0] = params[0].substr(1, params[0].length()-1);
3176                         }
3177                         if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$'))
3178                         {
3179                                 // special routing for private messages/notices
3180                                 userrec* d = Srv->FindNick(params[0]);
3181                                 if (d)
3182                                 {
3183                                         std::deque<std::string> par;
3184                                         par.push_back(params[0]);
3185                                         par.push_back(":"+params[1]);
3186                                         DoOneToOne(prefix,command.c_str(),par,d->server);
3187                                         return true;
3188                                 }
3189                         }
3190                         else if (*(params[0].c_str()) == '$')
3191                         {
3192                                 std::deque<std::string> par;
3193                                 par.push_back(params[0]);
3194                                 par.push_back(":"+params[1]);
3195                                 DoOneToAllButSender(prefix,command.c_str(),par,omitroute->GetName());
3196                                 return true;
3197                         }
3198                         else
3199                         {
3200                                 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
3201                                 chanrec* c = Srv->FindChannel(params[0]);
3202                                 if (c)
3203                                 {
3204                                         std::deque<TreeServer*> list;
3205                                         GetListOfServersForChannel(c,list);
3206                                         log(DEBUG,"Got a list of %d servers",list.size());
3207                                         unsigned int lsize = list.size();
3208                                         for (unsigned int i = 0; i < lsize; i++)
3209                                         {
3210                                                 TreeSocket* Sock = list[i]->GetSocket();
3211                                                 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
3212                                                 {
3213                                                         log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
3214                                                         Sock->WriteLine(data);
3215                                                 }
3216                                         }
3217                                         return true;
3218                                 }
3219                         }
3220                 }
3221         }
3222         unsigned int items = TreeRoot->ChildCount();
3223         for (unsigned int x = 0; x < items; x++)
3224         {
3225                 TreeServer* Route = TreeRoot->GetChild(x);
3226                 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3227                 {
3228                         TreeSocket* Sock = Route->GetSocket();
3229                         Sock->WriteLine(data);
3230                 }
3231         }
3232         return true;
3233 }
3234
3235 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> &params, std::string omit)
3236 {
3237         TreeServer* omitroute = BestRouteTo(omit);
3238         std::string FullLine = ":" + prefix + " " + command;
3239         unsigned int words = params.size();
3240         for (unsigned int x = 0; x < words; x++)
3241         {
3242                 FullLine = FullLine + " " + params[x];
3243         }
3244         unsigned int items = TreeRoot->ChildCount();
3245         for (unsigned int x = 0; x < items; x++)
3246         {
3247                 TreeServer* Route = TreeRoot->GetChild(x);
3248                 // Send the line IF:
3249                 // The route has a socket (its a direct connection)
3250                 // The route isnt the one to be omitted
3251                 // The route isnt the path to the one to be omitted
3252                 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3253                 {
3254                         TreeSocket* Sock = Route->GetSocket();
3255                         Sock->WriteLine(FullLine);
3256                 }
3257         }
3258         return true;
3259 }
3260
3261 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> &params)
3262 {
3263         std::string FullLine = ":" + prefix + " " + command;
3264         unsigned int words = params.size();
3265         for (unsigned int x = 0; x < words; x++)
3266         {
3267                 FullLine = FullLine + " " + params[x];
3268         }
3269         unsigned int items = TreeRoot->ChildCount();
3270         for (unsigned int x = 0; x < items; x++)
3271         {
3272                 TreeServer* Route = TreeRoot->GetChild(x);
3273                 if (Route->GetSocket())
3274                 {
3275                         TreeSocket* Sock = Route->GetSocket();
3276                         Sock->WriteLine(FullLine);
3277                 }
3278         }
3279         return true;
3280 }
3281
3282 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> &params, std::string target)
3283 {
3284         TreeServer* Route = BestRouteTo(target);
3285         if (Route)
3286         {
3287                 std::string FullLine = ":" + prefix + " " + command;
3288                 unsigned int words = params.size();
3289                 for (unsigned int x = 0; x < words; x++)
3290                 {
3291                         FullLine = FullLine + " " + params[x];
3292                 }
3293                 if (Route->GetSocket())
3294                 {
3295                         TreeSocket* Sock = Route->GetSocket();
3296                         Sock->WriteLine(FullLine);
3297                 }
3298                 return true;
3299         }
3300         else
3301         {
3302                 return true;
3303         }
3304 }
3305
3306 std::vector<TreeSocket*> Bindings;
3307
3308 void ReadConfiguration(bool rebind)
3309 {
3310         Conf = new ConfigReader;
3311         if (rebind)
3312         {
3313                 for (int j =0; j < Conf->Enumerate("bind"); j++)
3314                 {
3315                         std::string Type = Conf->ReadValue("bind","type",j);
3316                         std::string IP = Conf->ReadValue("bind","address",j);
3317                         long Port = Conf->ReadInteger("bind","port",j,true);
3318                         if (Type == "servers")
3319                         {
3320                                 if (IP == "*")
3321                                 {
3322                                         IP = "";
3323                                 }
3324                                 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
3325                                 if (listener->GetState() == I_LISTENING)
3326                                 {
3327                                         Srv->AddSocket(listener);
3328                                         Bindings.push_back(listener);
3329                                 }
3330                                 else
3331                                 {
3332                                         log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
3333                                         listener->Close();
3334                                         DELETE(listener);
3335                                 }
3336                         }
3337                 }
3338         }
3339         FlatLinks = Conf->ReadFlag("options","flatlinks",0);
3340         HideULines = Conf->ReadFlag("options","hideulines",0);
3341         LinkBlocks.clear();
3342         ValidIPs.clear();
3343         for (int j =0; j < Conf->Enumerate("link"); j++)
3344         {
3345                 Link L;
3346                 L.Name = (Conf->ReadValue("link","name",j)).c_str();
3347                 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
3348                 L.Port = Conf->ReadInteger("link","port",j,true);
3349                 L.SendPass = Conf->ReadValue("link","sendpass",j);
3350                 L.RecvPass = Conf->ReadValue("link","recvpass",j);
3351                 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
3352                 L.EncryptionKey =  Conf->ReadValue("link","encryptionkey",j);
3353                 L.HiddenFromStats = Conf->ReadFlag("link","hidden",j);
3354                 L.NextConnectTime = time(NULL) + L.AutoConnect;
3355                 /* Bugfix by brain, do not allow people to enter bad configurations */
3356                 if ((L.IPAddr != "") && (L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
3357                 {
3358                         ValidIPs.push_back(L.IPAddr);
3359
3360                         /* Needs resolving */
3361                         insp_inaddr binip;
3362                         if (insp_aton(L.IPAddr.c_str(), &binip) < 1)
3363                         {
3364                                 try
3365                                 {
3366                                         SecurityIPResolver* sr = new SecurityIPResolver(L.IPAddr, L);
3367                                         Srv->AddResolver(sr);
3368                                 }
3369                                 catch (ModuleException& e)
3370                                 {
3371                                         log(DEBUG,"Error in resolver: %s",e.GetReason());
3372                                 }
3373                         }
3374
3375                         LinkBlocks.push_back(L);
3376                         log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
3377                 }
3378                 else
3379                 {
3380                         if (L.IPAddr == "")
3381                         {
3382                                 log(DEFAULT,"Invalid configuration for server '%s', IP address not defined!",L.Name.c_str());
3383                         }
3384                         else if (L.RecvPass == "")
3385                         {
3386                                 log(DEFAULT,"Invalid configuration for server '%s', recvpass not defined!",L.Name.c_str());
3387                         }
3388                         else if (L.SendPass == "")
3389                         {
3390                                 log(DEFAULT,"Invalid configuration for server '%s', sendpass not defined!",L.Name.c_str());
3391                         }
3392                         else if (L.Name == "")
3393                         {
3394                                 log(DEFAULT,"Invalid configuration, link tag without a name!");
3395                         }
3396                         else if (!L.Port)
3397                         {
3398                                 log(DEFAULT,"Invalid configuration for server '%s', no port specified!",L.Name.c_str());
3399                         }
3400                 }
3401         }
3402         DELETE(Conf);
3403 }
3404
3405
3406 class ModuleSpanningTree : public Module
3407 {
3408         std::vector<TreeSocket*> Bindings;
3409         int line;
3410         int NumServers;
3411         unsigned int max_local;
3412         unsigned int max_global;
3413         cmd_rconnect* command_rconnect;
3414
3415  public:
3416
3417         ModuleSpanningTree(Server* Me)
3418                 : Module::Module(Me), max_local(0), max_global(0)
3419         {
3420                 Srv = Me;
3421                 Bindings.clear();
3422
3423                 // Create the root of the tree
3424                 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
3425
3426                 ReadConfiguration(true);
3427
3428                 command_rconnect = new cmd_rconnect(this);
3429                 Srv->AddCommand(command_rconnect);
3430         }
3431
3432         void ShowLinks(TreeServer* Current, userrec* user, int hops)
3433         {
3434                 std::string Parent = TreeRoot->GetName();
3435                 if (Current->GetParent())
3436                 {
3437                         Parent = Current->GetParent()->GetName();
3438                 }
3439                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
3440                 {
3441                         if ((HideULines) && (Srv->IsUlined(Current->GetChild(q)->GetName())))
3442                         {
3443                                 if (*user->oper)
3444                                 {
3445                                          ShowLinks(Current->GetChild(q),user,hops+1);
3446                                 }
3447                         }
3448                         else
3449                         {
3450                                 ShowLinks(Current->GetChild(q),user,hops+1);
3451                         }
3452                 }
3453                 /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
3454                 if ((HideULines) && (Srv->IsUlined(Current->GetName())) && (!*user->oper))
3455                         return;
3456                 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),(FlatLinks && (!*user->oper)) ? Srv->GetServerName().c_str() : Parent.c_str(),(FlatLinks && (!*user->oper)) ? 0 : hops,Current->GetDesc().c_str());
3457         }
3458
3459         int CountLocalServs()
3460         {
3461                 return TreeRoot->ChildCount();
3462         }
3463
3464         int CountServs()
3465         {
3466                 return serverlist.size();
3467         }
3468
3469         void HandleLinks(const char** parameters, int pcnt, userrec* user)
3470         {
3471                 ShowLinks(TreeRoot,user,0);
3472                 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
3473                 return;
3474         }
3475
3476         void HandleLusers(const char** parameters, int pcnt, userrec* user)
3477         {
3478                 unsigned int n_users = usercnt();
3479
3480                 /* Only update these when someone wants to see them, more efficient */
3481                 if ((unsigned int)local_count() > max_local)
3482                         max_local = local_count();
3483                 if (n_users > max_global)
3484                         max_global = n_users;
3485
3486                 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,n_users-usercount_invisible(),usercount_invisible(),this->CountServs());
3487                 if (usercount_opers())
3488                         WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
3489                 if (usercount_unknown())
3490                         WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
3491                 if (chancount())
3492                         WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
3493                 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
3494                 WriteServ(user->fd,"265 %s :Current Local Users: %d  Max: %d",user->nick,local_count(),max_local);
3495                 WriteServ(user->fd,"266 %s :Current Global Users: %d  Max: %d",user->nick,n_users,max_global);
3496                 return;
3497         }
3498
3499         // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
3500
3501         void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80], float &totusers, float &totservers)
3502         {
3503                 if (line < 128)
3504                 {
3505                         for (int t = 0; t < depth; t++)
3506                         {
3507                                 matrix[line][t] = ' ';
3508                         }
3509
3510                         // For Aligning, we need to work out exactly how deep this thing is, and produce
3511                         // a 'Spacer' String to compensate.
3512                         char spacer[40];
3513
3514                         memset(spacer,' ',40);
3515                         if ((40 - Current->GetName().length() - depth) > 1) {
3516                                 spacer[40 - Current->GetName().length() - depth] = '\0';
3517                         }
3518                         else
3519                         {
3520                                 spacer[5] = '\0';
3521                         }
3522
3523                         float percent;
3524                         char text[80];
3525                         if (clientlist.size() == 0) {
3526                                 // If there are no users, WHO THE HELL DID THE /MAP?!?!?!
3527                                 percent = 0;
3528                         }
3529                         else
3530                         {
3531                                 percent = ((float)Current->GetUserCount() / (float)clientlist.size()) * 100;
3532                         }
3533                         snprintf(text, 80, "%s %s%5d [%5.2f%%]", Current->GetName().c_str(), spacer, Current->GetUserCount(), percent);
3534                         totusers += Current->GetUserCount();
3535                         totservers++;
3536                         strlcpy(&matrix[line][depth],text,80);
3537                         line++;
3538                         for (unsigned int q = 0; q < Current->ChildCount(); q++)
3539                         {
3540                                 if ((HideULines) && (Srv->IsUlined(Current->GetChild(q)->GetName())))
3541                                 {
3542                                         if (*user->oper)
3543                                         {
3544                                                 ShowMap(Current->GetChild(q),user,(FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
3545                                         }
3546                                 }
3547                                 else
3548                                 {
3549                                         ShowMap(Current->GetChild(q),user,(FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
3550                                 }
3551                         }
3552                 }
3553         }
3554
3555         int HandleStats(const char** parameters, int pcnt, userrec* user)
3556         {
3557                 if (pcnt > 1)
3558                 {
3559                         /* Remote STATS, the server is within the 2nd parameter */
3560                         std::deque<std::string> params;
3561                         params.push_back(parameters[0]);
3562                         params.push_back(parameters[1]);
3563                         /* Send it out remotely, generate no reply yet */
3564                         TreeServer* s = FindServerMask(parameters[1]);
3565                         if (s)
3566                         {
3567                                 params[1] = s->GetName();
3568                                 DoOneToOne(user->nick, "STATS", params, s->GetName());
3569                         }
3570                         return 1;
3571                 }
3572                 return 0;
3573         }
3574
3575         // Ok, prepare to be confused.
3576         // After much mulling over how to approach this, it struck me that
3577         // the 'usual' way of doing a /MAP isnt the best way. Instead of
3578         // keeping track of a ton of ascii characters, and line by line
3579         // under recursion working out where to place them using multiplications
3580         // and divisons, we instead render the map onto a backplane of characters
3581         // (a character matrix), then draw the branches as a series of "L" shapes
3582         // from the nodes. This is not only friendlier on CPU it uses less stack.
3583
3584         void HandleMap(const char** parameters, int pcnt, userrec* user)
3585         {
3586                 // This array represents a virtual screen which we will
3587                 // "scratch" draw to, as the console device of an irc
3588                 // client does not provide for a proper terminal.
3589                 float totusers = 0;
3590                 float totservers = 0;
3591                 char matrix[128][80];
3592                 for (unsigned int t = 0; t < 128; t++)
3593                 {
3594                         matrix[t][0] = '\0';
3595                 }
3596                 line = 0;
3597                 // The only recursive bit is called here.
3598                 ShowMap(TreeRoot,user,0,matrix,totusers,totservers);
3599                 // Process each line one by one. The algorithm has a limit of
3600                 // 128 servers (which is far more than a spanning tree should have
3601                 // anyway, so we're ok). This limit can be raised simply by making
3602                 // the character matrix deeper, 128 rows taking 10k of memory.
3603                 for (int l = 1; l < line; l++)
3604                 {
3605                         // scan across the line looking for the start of the
3606                         // servername (the recursive part of the algorithm has placed
3607                         // the servers at indented positions depending on what they
3608                         // are related to)
3609                         int first_nonspace = 0;
3610                         while (matrix[l][first_nonspace] == ' ')
3611                         {
3612                                 first_nonspace++;
3613                         }
3614                         first_nonspace--;
3615                         // Draw the `- (corner) section: this may be overwritten by
3616                         // another L shape passing along the same vertical pane, becoming
3617                         // a |- (branch) section instead.
3618                         matrix[l][first_nonspace] = '-';
3619                         matrix[l][first_nonspace-1] = '`';
3620                         int l2 = l - 1;
3621                         // Draw upwards until we hit the parent server, causing possibly
3622                         // other corners (`-) to become branches (|-)
3623                         while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
3624                         {
3625                                 matrix[l2][first_nonspace-1] = '|';
3626                                 l2--;
3627                         }
3628                 }
3629                 // dump the whole lot to the user. This is the easy bit, honest.
3630                 for (int t = 0; t < line; t++)
3631                 {
3632                         WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
3633                 }
3634                 float avg_users = totusers / totservers;
3635                 WriteServ(user->fd,"270 %s :%.0f server%s and %.0f user%s, average %.2f users per server",user->nick,totservers,(totservers > 1 ? "s" : ""),totusers,(totusers > 1 ? "s" : ""),avg_users);
3636         WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
3637                 return;
3638         }
3639
3640         int HandleSquit(const char** parameters, int pcnt, userrec* user)
3641         {
3642                 TreeServer* s = FindServerMask(parameters[0]);
3643                 if (s)
3644                 {
3645                         if (s == TreeRoot)
3646                         {
3647                                  WriteServ(user->fd,"NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
3648                                 return 1;
3649                         }
3650                         TreeSocket* sock = s->GetSocket();
3651                         if (sock)
3652                         {
3653                                 log(DEBUG,"Splitting server %s",s->GetName().c_str());
3654                                 WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
3655                                 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
3656                                 Srv->RemoveSocket(sock);
3657                         }
3658                         else
3659                         {
3660                                 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
3661                         }
3662                 }
3663                 else
3664                 {
3665                          WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
3666                 }
3667                 return 1;
3668         }
3669
3670         int HandleTime(const char** parameters, int pcnt, userrec* user)
3671         {
3672                 if ((IS_LOCAL(user)) && (pcnt))
3673                 {
3674                         TreeServer* found = FindServerMask(parameters[0]);
3675                         if (found)
3676                         {
3677                                 // we dont' override for local server
3678                                 if (found == TreeRoot)
3679                                         return 0;
3680                                 
3681                                 std::deque<std::string> params;
3682                                 params.push_back(found->GetName());
3683                                 params.push_back(user->nick);
3684                                 DoOneToOne(Srv->GetServerName(),"TIME",params,found->GetName());
3685                         }
3686                         else
3687                         {
3688                                 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
3689                         }
3690                 }
3691                 return 1;
3692         }
3693
3694         int HandleRemoteWhois(const char** parameters, int pcnt, userrec* user)
3695         {
3696                 if ((IS_LOCAL(user)) && (pcnt > 1))
3697                 {
3698                         userrec* remote = Srv->FindNick(parameters[1]);
3699                         if ((remote) && (remote->fd < 0))
3700                         {
3701                                 std::deque<std::string> params;
3702                                 params.push_back(parameters[1]);
3703                                 DoOneToOne(user->nick,"IDLE",params,remote->server);
3704                                 return 1;
3705                         }
3706                         else if (!remote)
3707                         {
3708                                 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
3709                                 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
3710                                 return 1;
3711                         }
3712                 }
3713                 return 0;
3714         }
3715
3716         void DoPingChecks(time_t curtime)
3717         {
3718                 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
3719                 {
3720                         TreeServer* serv = TreeRoot->GetChild(j);
3721                         TreeSocket* sock = serv->GetSocket();
3722                         if (sock)
3723                         {
3724                                 if (curtime >= serv->NextPingTime())
3725                                 {
3726                                         if (serv->AnsweredLastPing())
3727                                         {
3728                                                 sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
3729                                                 serv->SetNextPingTime(curtime + 120);
3730                                         }
3731                                         else
3732                                         {
3733                                                 // they didnt answer, boot them
3734                                                 WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
3735                                                 sock->Squit(serv,"Ping timeout");
3736                                                 Srv->RemoveSocket(sock);
3737                                                 return;
3738                                         }
3739                                 }
3740                         }
3741                 }
3742         }
3743
3744         void AutoConnectServers(time_t curtime)
3745         {
3746                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
3747                 {
3748                         if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
3749                         {
3750                                 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
3751                                 x->NextConnectTime = curtime + x->AutoConnect;
3752                                 TreeServer* CheckDupe = FindServer(x->Name.c_str());
3753                                 if (!CheckDupe)
3754                                 {
3755                                         // an autoconnected server is not connected. Check if its time to connect it
3756                                         WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
3757
3758                                         insp_inaddr binip;
3759
3760                                         /* Do we already have an IP? If so, no need to resolve it. */
3761                                         if (insp_aton(x->IPAddr.c_str(), &binip) > 0)
3762                                         {
3763                                                 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name.c_str());
3764                                                 if (newsocket->GetFd() > -1)
3765                                                 {
3766                                                         Srv->AddSocket(newsocket);
3767                                                 }
3768                                                 else
3769                                                 {
3770                                                         WriteOpers("*** AUTOCONNECT: Error autoconnecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
3771                                                         delete newsocket;
3772                                                 }
3773                                         }
3774                                         else
3775                                         {
3776                                                 try
3777                                                 {
3778                                                         ServernameResolver* snr = new ServernameResolver(x->IPAddr, *x);
3779                                                         Srv->AddResolver(snr);
3780                                                 }
3781                                                 catch (ModuleException& e)
3782                                                 {
3783                                                         log(DEBUG,"Error in resolver: %s",e.GetReason());
3784                                                 }
3785                                         }
3786
3787                                 }
3788                         }
3789                 }
3790         }
3791
3792         int HandleVersion(const char** parameters, int pcnt, userrec* user)
3793         {
3794                 // we've already checked if pcnt > 0, so this is safe
3795                 TreeServer* found = FindServerMask(parameters[0]);
3796                 if (found)
3797                 {
3798                         std::string Version = found->GetVersion();
3799                         WriteServ(user->fd,"351 %s :%s",user->nick,Version.c_str());
3800                         if (found == TreeRoot)
3801                         {
3802                                 std::stringstream out(Config->data005);
3803                                 std::string token = "";
3804                                 std::string line5 = "";
3805                                 int token_counter = 0;
3806
3807                                 while (!out.eof())
3808                                 {
3809                                         out >> token;
3810                                         line5 = line5 + token + " ";   
3811                                         token_counter++;
3812
3813                                         if ((token_counter >= 13) || (out.eof() == true))
3814                                         {
3815                                                 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
3816                                                 line5 = "";
3817                                                 token_counter = 0;
3818                                         }
3819                                 }
3820                         }
3821                 }
3822                 else
3823                 {
3824                         WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
3825                 }
3826                 return 1;
3827         }
3828         
3829         int HandleConnect(const char** parameters, int pcnt, userrec* user)
3830         {
3831                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
3832                 {
3833                         if (Srv->MatchText(x->Name.c_str(),parameters[0]))
3834                         {
3835                                 TreeServer* CheckDupe = FindServer(x->Name.c_str());
3836                                 if (!CheckDupe)
3837                                 {
3838                                         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);
3839                                         insp_inaddr binip;
3840
3841                                         /* Do we already have an IP? If so, no need to resolve it. */
3842                                         if (insp_aton(x->IPAddr.c_str(), &binip) > 0)
3843                                         {
3844                                                 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name.c_str());
3845                                                 if (newsocket->GetFd() > -1)
3846                                                 {
3847                                                         Srv->AddSocket(newsocket);
3848                                                 }
3849                                                 else
3850                                                 {
3851                                                         WriteOpers("*** CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
3852                                                         delete newsocket;
3853                                                 }
3854                                         }
3855                                         else
3856                                         {
3857                                                 try
3858                                                 {
3859                                                         ServernameResolver* snr = new ServernameResolver(x->IPAddr, *x);
3860                                                         Srv->AddResolver(snr);
3861                                                 }
3862                                                 catch (ModuleException& e)
3863                                                 {
3864                                                         log(DEBUG,"Error in resolver: %s",e.GetReason());
3865                                                 }
3866                                         }
3867                                         return 1;
3868                                 }
3869                                 else
3870                                 {
3871                                         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());
3872                                         return 1;
3873                                 }
3874                         }
3875                 }
3876                 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
3877                 return 1;
3878         }
3879
3880         virtual int OnStats(char statschar, userrec* user, string_list &results)
3881         {
3882                 if (statschar == 'c')
3883                 {
3884                         for (unsigned int i = 0; i < LinkBlocks.size(); i++)
3885                         {
3886                                 results.push_back(Srv->GetServerName()+" 213 "+user->nick+" C *@"+(LinkBlocks[i].HiddenFromStats ? "<hidden>" : LinkBlocks[i].IPAddr)+" * "+LinkBlocks[i].Name.c_str()+" "+ConvToStr(LinkBlocks[i].Port)+" "+(LinkBlocks[i].EncryptionKey != "" ? 'e' : '-')+(LinkBlocks[i].AutoConnect ? 'a' : '-')+'s');
3887                                 results.push_back(Srv->GetServerName()+" 244 "+user->nick+" H * * "+LinkBlocks[i].Name.c_str());
3888                         }
3889                         results.push_back(Srv->GetServerName()+" 219 "+user->nick+" "+statschar+" :End of /STATS report");
3890                         WriteOpers("*** Notice: %s '%c' requested by %s (%s@%s)",(!strcmp(user->server,Config->ServerName) ? "Stats" : "Remote stats"),statschar,user->nick,user->ident,user->host);
3891                         return 1;
3892                 }
3893                 return 0;
3894         }
3895
3896         virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated)
3897         {
3898                 /* If the command doesnt appear to be valid, we dont want to mess with it. */
3899                 if (!validated)
3900                         return 0;
3901
3902                 if (command == "CONNECT")
3903                 {
3904                         return this->HandleConnect(parameters,pcnt,user);
3905                 }
3906                 else if (command == "STATS")
3907                 {
3908                         return this->HandleStats(parameters,pcnt,user);
3909                 }
3910                 else if (command == "SQUIT")
3911                 {
3912                         return this->HandleSquit(parameters,pcnt,user);
3913                 }
3914                 else if (command == "MAP")
3915                 {
3916                         this->HandleMap(parameters,pcnt,user);
3917                         return 1;
3918                 }
3919                 else if ((command == "TIME") && (pcnt > 0))
3920                 {
3921                         return this->HandleTime(parameters,pcnt,user);
3922                 }
3923                 else if (command == "LUSERS")
3924                 {
3925                         this->HandleLusers(parameters,pcnt,user);
3926                         return 1;
3927                 }
3928                 else if (command == "LINKS")
3929                 {
3930                         this->HandleLinks(parameters,pcnt,user);
3931                         return 1;
3932                 }
3933                 else if (command == "WHOIS")
3934                 {
3935                         if (pcnt > 1)
3936                         {
3937                                 // remote whois
3938                                 return this->HandleRemoteWhois(parameters,pcnt,user);
3939                         }
3940                 }
3941                 else if ((command == "VERSION") && (pcnt > 0))
3942                 {
3943                         this->HandleVersion(parameters,pcnt,user);
3944                         return 1;
3945                 }
3946                 else if (Srv->IsValidModuleCommand(command, pcnt, user))
3947                 {
3948                         // this bit of code cleverly routes all module commands
3949                         // to all remote severs *automatically* so that modules
3950                         // can just handle commands locally, without having
3951                         // to have any special provision in place for remote
3952                         // commands and linking protocols.
3953                         std::deque<std::string> params;
3954                         params.clear();
3955                         for (int j = 0; j < pcnt; j++)
3956                         {
3957                                 if (strchr(parameters[j],' '))
3958                                 {
3959                                         params.push_back(":" + std::string(parameters[j]));
3960                                 }
3961                                 else
3962                                 {
3963                                         params.push_back(std::string(parameters[j]));
3964                                 }
3965                         }
3966                         log(DEBUG,"Globally route '%s'",command.c_str());
3967                         DoOneToMany(user->nick,command,params);
3968                 }
3969                 return 0;
3970         }
3971
3972         virtual void OnGetServerDescription(const std::string &servername,std::string &description)
3973         {
3974                 TreeServer* s = FindServer(servername);
3975                 if (s)
3976                 {
3977                         description = s->GetDesc();
3978                 }
3979         }
3980
3981         virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
3982         {
3983                 if (IS_LOCAL(source))
3984                 {
3985                         std::deque<std::string> params;
3986                         params.push_back(dest->nick);
3987                         params.push_back(channel->name);
3988                         DoOneToMany(source->nick,"INVITE",params);
3989                 }
3990         }
3991
3992         virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, const std::string &topic)
3993         {
3994                 std::deque<std::string> params;
3995                 params.push_back(chan->name);
3996                 params.push_back(":"+topic);
3997                 DoOneToMany(user->nick,"TOPIC",params);
3998         }
3999
4000         virtual void OnWallops(userrec* user, const std::string &text)
4001         {
4002                 if (IS_LOCAL(user))
4003                 {
4004                         std::deque<std::string> params;
4005                         params.push_back(":"+text);
4006                         DoOneToMany(user->nick,"WALLOPS",params);
4007                 }
4008         }
4009
4010         virtual void OnUserNotice(userrec* user, void* dest, int target_type, const std::string &text, char status)
4011         {
4012                 if (target_type == TYPE_USER)
4013                 {
4014                         userrec* d = (userrec*)dest;
4015                         if ((d->fd < 0) && (IS_LOCAL(user)))
4016                         {
4017                                 std::deque<std::string> params;
4018                                 params.clear();
4019                                 params.push_back(d->nick);
4020                                 params.push_back(":"+text);
4021                                 DoOneToOne(user->nick,"NOTICE",params,d->server);
4022                         }
4023                 }
4024                 else if (target_type == TYPE_CHANNEL)
4025                 {
4026                         if (IS_LOCAL(user))
4027                         {
4028                                 chanrec *c = (chanrec*)dest;
4029                                 std::string cname = c->name;
4030                                 if (status)
4031                                         cname = status + cname;
4032                                 std::deque<TreeServer*> list;
4033                                 GetListOfServersForChannel(c,list);
4034                                 unsigned int ucount = list.size();
4035                                 for (unsigned int i = 0; i < ucount; i++)
4036                                 {
4037                                         TreeSocket* Sock = list[i]->GetSocket();
4038                                         if (Sock)
4039                                                 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+cname+" :"+text);
4040                                 }
4041                         }
4042                 }
4043                 else if (target_type == TYPE_SERVER)
4044                 {
4045                         if (IS_LOCAL(user))
4046                         {
4047                                 char* target = (char*)dest;
4048                                 std::deque<std::string> par;
4049                                 par.push_back(target);
4050                                 par.push_back(":"+text);
4051                                 DoOneToMany(user->nick,"NOTICE",par);
4052                         }
4053                 }
4054         }
4055
4056         virtual void OnUserMessage(userrec* user, void* dest, int target_type, const std::string &text, char status)
4057         {
4058                 if (target_type == TYPE_USER)
4059                 {
4060                         // route private messages which are targetted at clients only to the server
4061                         // which needs to receive them
4062                         userrec* d = (userrec*)dest;
4063                         if ((d->fd < 0) && (IS_LOCAL(user)))
4064                         {
4065                                 std::deque<std::string> params;
4066                                 params.clear();
4067                                 params.push_back(d->nick);
4068                                 params.push_back(":"+text);
4069                                 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
4070                         }
4071                 }
4072                 else if (target_type == TYPE_CHANNEL)
4073                 {
4074                         if (IS_LOCAL(user))
4075                         {
4076                                 chanrec *c = (chanrec*)dest;
4077                                 std::string cname = c->name;
4078                                 if (status)
4079                                         cname = status + cname;
4080                                 std::deque<TreeServer*> list;
4081                                 GetListOfServersForChannel(c,list);
4082                                 unsigned int ucount = list.size();
4083                                 for (unsigned int i = 0; i < ucount; i++)
4084                                 {
4085                                         TreeSocket* Sock = list[i]->GetSocket();
4086                                         if (Sock)
4087                                                 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+cname+" :"+text);
4088                                 }
4089                         }
4090                 }
4091                 else if (target_type == TYPE_SERVER)
4092                 {
4093                         if (IS_LOCAL(user))
4094                         {
4095                                 char* target = (char*)dest;
4096                                 std::deque<std::string> par;
4097                                 par.push_back(target);
4098                                 par.push_back(":"+text);
4099                                 DoOneToMany(user->nick,"PRIVMSG",par);
4100                         }
4101                 }
4102         }
4103
4104         virtual void OnBackgroundTimer(time_t curtime)
4105         {
4106                 AutoConnectServers(curtime);
4107                 DoPingChecks(curtime);
4108         }
4109
4110         virtual void OnUserJoin(userrec* user, chanrec* channel)
4111         {
4112                 // Only do this for local users
4113                 if (IS_LOCAL(user))
4114                 {
4115                         std::deque<std::string> params;
4116                         params.clear();
4117                         params.push_back(channel->name);
4118
4119                         if (channel->GetUserCounter() > 1)
4120                         {
4121                                 // not the first in the channel
4122                                 DoOneToMany(user->nick,"JOIN",params);
4123                         }
4124                         else
4125                         {
4126                                 // first in the channel, set up their permissions
4127                                 // and the channel TS with FJOIN.
4128                                 char ts[24];
4129                                 snprintf(ts,24,"%lu",(unsigned long)channel->age);
4130                                 params.clear();
4131                                 params.push_back(channel->name);
4132                                 params.push_back(ts);
4133                                 params.push_back("@"+std::string(user->nick));
4134                                 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
4135                         }
4136                 }
4137         }
4138
4139         virtual void OnChangeHost(userrec* user, const std::string &newhost)
4140         {
4141                 // only occurs for local clients
4142                 if (user->registered != REG_ALL)
4143                         return;
4144                 std::deque<std::string> params;
4145                 params.push_back(newhost);
4146                 DoOneToMany(user->nick,"FHOST",params);
4147         }
4148
4149         virtual void OnChangeName(userrec* user, const std::string &gecos)
4150         {
4151                 // only occurs for local clients
4152                 if (user->registered != REG_ALL)
4153                         return;
4154                 std::deque<std::string> params;
4155                 params.push_back(gecos);
4156                 DoOneToMany(user->nick,"FNAME",params);
4157         }
4158
4159         virtual void OnUserPart(userrec* user, chanrec* channel, const std::string &partmessage)
4160         {
4161                 if (IS_LOCAL(user))
4162                 {
4163                         std::deque<std::string> params;
4164                         params.push_back(channel->name);
4165                         if (partmessage != "")
4166                                 params.push_back(":"+partmessage);
4167                         DoOneToMany(user->nick,"PART",params);
4168                 }
4169         }
4170
4171         virtual void OnUserConnect(userrec* user)
4172         {
4173                 char agestr[MAXBUF];
4174                 if (IS_LOCAL(user))
4175                 {
4176                         std::deque<std::string> params;
4177                         snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
4178                         params.push_back(agestr);
4179                         params.push_back(user->nick);
4180                         params.push_back(user->host);
4181                         params.push_back(user->dhost);
4182                         params.push_back(user->ident);
4183                         params.push_back("+"+std::string(user->FormatModes()));
4184                         params.push_back(user->GetIPString());
4185                         params.push_back(":"+std::string(user->fullname));
4186                         DoOneToMany(Srv->GetServerName(),"NICK",params);
4187
4188                         // User is Local, change needs to be reflected!
4189                         TreeServer* SourceServer = FindServer(user->server);
4190                         if (SourceServer)
4191                         {
4192                                 SourceServer->AddUserCount();
4193                         }
4194
4195                 }
4196         }
4197
4198         virtual void OnUserQuit(userrec* user, const std::string &reason)
4199         {
4200                 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
4201                 {
4202                         std::deque<std::string> params;
4203                         params.push_back(":"+reason);
4204                         DoOneToMany(user->nick,"QUIT",params);
4205                 }
4206                 // Regardless, We need to modify the user Counts..
4207                 TreeServer* SourceServer = FindServer(user->server);
4208                 if (SourceServer)
4209                 {
4210                         SourceServer->DelUserCount();
4211                 }
4212
4213         }
4214
4215         virtual void OnUserPostNick(userrec* user, const std::string &oldnick)
4216         {
4217                 if (IS_LOCAL(user))
4218                 {
4219                         std::deque<std::string> params;
4220                         params.push_back(user->nick);
4221                         DoOneToMany(oldnick,"NICK",params);
4222                 }
4223         }
4224
4225         virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, const std::string &reason)
4226         {
4227                 if ((source) && (IS_LOCAL(source)))
4228                 {
4229                         std::deque<std::string> params;
4230                         params.push_back(chan->name);
4231                         params.push_back(user->nick);
4232                         params.push_back(":"+reason);
4233                         DoOneToMany(source->nick,"KICK",params);
4234                 }
4235                 else if (!source)
4236                 {
4237                         std::deque<std::string> params;
4238                         params.push_back(chan->name);
4239                         params.push_back(user->nick);
4240                         params.push_back(":"+reason);
4241                         DoOneToMany(Srv->GetServerName(),"KICK",params);
4242                 }
4243         }
4244
4245         virtual void OnRemoteKill(userrec* source, userrec* dest, const std::string &reason)
4246         {
4247                 std::deque<std::string> params;
4248                 params.push_back(dest->nick);
4249                 params.push_back(":"+reason);
4250                 DoOneToMany(source->nick,"KILL",params);
4251         }
4252
4253         virtual void OnRehash(const std::string &parameter)
4254         {
4255                 if (parameter != "")
4256                 {
4257                         std::deque<std::string> params;
4258                         params.push_back(parameter);
4259                         DoOneToMany(Srv->GetServerName(),"REHASH",params);
4260                         // check for self
4261                         if (Srv->MatchText(Srv->GetServerName(),parameter))
4262                         {
4263                                 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
4264                                 Srv->RehashServer();
4265                         }
4266                 }
4267                 ReadConfiguration(false);
4268         }
4269
4270         // note: the protocol does not allow direct umode +o except
4271         // via NICK with 8 params. sending OPERTYPE infers +o modechange
4272         // locally.
4273         virtual void OnOper(userrec* user, const std::string &opertype)
4274         {
4275                 if (IS_LOCAL(user))
4276                 {
4277                         std::deque<std::string> params;
4278                         params.push_back(opertype);
4279                         DoOneToMany(user->nick,"OPERTYPE",params);
4280                 }
4281         }
4282
4283         void OnLine(userrec* source, const std::string &host, bool adding, char linetype, long duration, const std::string &reason)
4284         {
4285                 if (IS_LOCAL(source))
4286                 {
4287                         char type[8];
4288                         snprintf(type,8,"%cLINE",linetype);
4289                         std::string stype = type;
4290                         if (adding)
4291                         {
4292                                 char sduration[MAXBUF];
4293                                 snprintf(sduration,MAXBUF,"%ld",duration);
4294                                 std::deque<std::string> params;
4295                                 params.push_back(host);
4296                                 params.push_back(sduration);
4297                                 params.push_back(":"+reason);
4298                                 DoOneToMany(source->nick,stype,params);
4299                         }
4300                         else
4301                         {
4302                                 std::deque<std::string> params;
4303                                 params.push_back(host);
4304                                 DoOneToMany(source->nick,stype,params);
4305                         }
4306                 }
4307         }
4308
4309         virtual void OnAddGLine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
4310         {
4311                 OnLine(source,hostmask,true,'G',duration,reason);
4312         }
4313         
4314         virtual void OnAddZLine(long duration, userrec* source, const std::string &reason, const std::string &ipmask)
4315         {
4316                 OnLine(source,ipmask,true,'Z',duration,reason);
4317         }
4318
4319         virtual void OnAddQLine(long duration, userrec* source, const std::string &reason, const std::string &nickmask)
4320         {
4321                 OnLine(source,nickmask,true,'Q',duration,reason);
4322         }
4323
4324         virtual void OnAddELine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
4325         {
4326                 OnLine(source,hostmask,true,'E',duration,reason);
4327         }
4328
4329         virtual void OnDelGLine(userrec* source, const std::string &hostmask)
4330         {
4331                 OnLine(source,hostmask,false,'G',0,"");
4332         }
4333
4334         virtual void OnDelZLine(userrec* source, const std::string &ipmask)
4335         {
4336                 OnLine(source,ipmask,false,'Z',0,"");
4337         }
4338
4339         virtual void OnDelQLine(userrec* source, const std::string &nickmask)
4340         {
4341                 OnLine(source,nickmask,false,'Q',0,"");
4342         }
4343
4344         virtual void OnDelELine(userrec* source, const std::string &hostmask)
4345         {
4346                 OnLine(source,hostmask,false,'E',0,"");
4347         }
4348
4349         virtual void OnMode(userrec* user, void* dest, int target_type, const std::string &text)
4350         {
4351                 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
4352                 {
4353                         if (target_type == TYPE_USER)
4354                         {
4355                                 userrec* u = (userrec*)dest;
4356                                 std::deque<std::string> params;
4357                                 params.push_back(u->nick);
4358                                 params.push_back(text);
4359                                 DoOneToMany(user->nick,"MODE",params);
4360                         }
4361                         else
4362                         {
4363                                 chanrec* c = (chanrec*)dest;
4364                                 std::deque<std::string> params;
4365                                 params.push_back(c->name);
4366                                 params.push_back(text);
4367                                 DoOneToMany(user->nick,"MODE",params);
4368                         }
4369                 }
4370         }
4371
4372         virtual void OnSetAway(userrec* user)
4373         {
4374                 if (IS_LOCAL(user))
4375                 {
4376                         std::deque<std::string> params;
4377                         params.push_back(":"+std::string(user->awaymsg));
4378                         DoOneToMany(user->nick,"AWAY",params);
4379                 }
4380         }
4381
4382         virtual void OnCancelAway(userrec* user)
4383         {
4384                 if (IS_LOCAL(user))
4385                 {
4386                         std::deque<std::string> params;
4387                         params.clear();
4388                         DoOneToMany(user->nick,"AWAY",params);
4389                 }
4390         }
4391
4392         virtual void ProtoSendMode(void* opaque, int target_type, void* target, const std::string &modeline)
4393         {
4394                 TreeSocket* s = (TreeSocket*)opaque;
4395                 if (target)
4396                 {
4397                         if (target_type == TYPE_USER)
4398                         {
4399                                 userrec* u = (userrec*)target;
4400                                 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+ConvToStr(u->age)+" "+modeline);
4401                         }
4402                         else
4403                         {
4404                                 chanrec* c = (chanrec*)target;
4405                                 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" "+modeline);
4406                         }
4407                 }
4408         }
4409
4410         virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, const std::string &extname, const std::string &extdata)
4411         {
4412                 TreeSocket* s = (TreeSocket*)opaque;
4413                 if (target)
4414                 {
4415                         if (target_type == TYPE_USER)
4416                         {
4417                                 userrec* u = (userrec*)target;
4418                                 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+u->nick+" "+extname+" :"+extdata);
4419                         }
4420                         else if (target_type == TYPE_OTHER)
4421                         {
4422                                 s->WriteLine(":"+Srv->GetServerName()+" METADATA * "+extname+" :"+extdata);
4423                         }
4424                         else if (target_type == TYPE_CHANNEL)
4425                         {
4426                                 chanrec* c = (chanrec*)target;
4427                                 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+c->name+" "+extname+" :"+extdata);
4428                         }
4429                 }
4430         }
4431
4432         virtual void OnEvent(Event* event)
4433         {
4434                 if (event->GetEventID() == "send_metadata")
4435                 {
4436                         std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
4437                         if (params->size() < 3)
4438                                 return;
4439                         (*params)[2] = ":" + (*params)[2];
4440                         DoOneToMany(Srv->GetServerName(),"METADATA",*params);
4441                 }
4442                 else if (event->GetEventID() == "send_mode")
4443                 {
4444                         std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
4445                         if (params->size() < 2)
4446                                 return;
4447                         // Insert the TS value of the object, either userrec or chanrec
4448                         time_t ourTS = 0;
4449                         userrec* a = Srv->FindNick((*params)[0]);
4450                         if (a)
4451                         {
4452                                 ourTS = a->age;
4453                         }
4454                         else
4455                         {
4456                                 chanrec* a = Srv->FindChannel((*params)[0]);
4457                                 if (a)
4458                                 {
4459                                         ourTS = a->age;
4460                                 }
4461                         }
4462                         params->insert(params->begin() + 1,ConvToStr(ourTS));
4463                         DoOneToMany(Srv->GetServerName(),"FMODE",*params);
4464                 }
4465         }
4466
4467         virtual ~ModuleSpanningTree()
4468         {
4469         }
4470
4471         virtual Version GetVersion()
4472         {
4473                 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
4474         }
4475
4476         void Implements(char* List)
4477         {
4478                 List[I_OnPreCommand] = List[I_OnGetServerDescription] = List[I_OnUserInvite] = List[I_OnPostLocalTopicChange] = 1;
4479                 List[I_OnWallops] = List[I_OnUserNotice] = List[I_OnUserMessage] = List[I_OnBackgroundTimer] = 1;
4480                 List[I_OnUserJoin] = List[I_OnChangeHost] = List[I_OnChangeName] = List[I_OnUserPart] = List[I_OnUserConnect] = 1;
4481                 List[I_OnUserQuit] = List[I_OnUserPostNick] = List[I_OnUserKick] = List[I_OnRemoteKill] = List[I_OnRehash] = 1;
4482                 List[I_OnOper] = List[I_OnAddGLine] = List[I_OnAddZLine] = List[I_OnAddQLine] = List[I_OnAddELine] = 1;
4483                 List[I_OnDelGLine] = List[I_OnDelZLine] = List[I_OnDelQLine] = List[I_OnDelELine] = List[I_ProtoSendMode] = List[I_OnMode] = 1;
4484                 List[I_OnStats] = List[I_ProtoSendMetaData] = List[I_OnEvent] = List[I_OnSetAway] = List[I_OnCancelAway] = 1;
4485         }
4486
4487         /* It is IMPORTANT that m_spanningtree is the last module in the chain
4488          * so that any activity it sees is FINAL, e.g. we arent going to send out
4489          * a NICK message before m_cloaking has finished putting the +x on the user,
4490          * etc etc.
4491          * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
4492          * the module call queue.
4493          */
4494         Priority Prioritize()
4495         {
4496                 return PRIORITY_LAST;
4497         }
4498 };
4499
4500
4501 class ModuleSpanningTreeFactory : public ModuleFactory
4502 {
4503  public:
4504         ModuleSpanningTreeFactory()
4505         {
4506         }
4507         
4508         ~ModuleSpanningTreeFactory()
4509         {
4510         }
4511         
4512         virtual Module * CreateModule(Server* Me)
4513         {
4514                 TreeProtocolModule = new ModuleSpanningTree(Me);
4515                 return TreeProtocolModule;
4516         }
4517         
4518 };
4519
4520
4521 extern "C" void * init_module( void )
4522 {
4523         return new ModuleSpanningTreeFactory;
4524 }