]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree.cpp
43c7bb773af7247c31684ff422b37dbc92b45b94
[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->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                                 n = 0;
1152                                 modelist[0] = params[0].c_str();
1153                                 modelist[1] = to_keep.c_str();
1154
1155                                 for (unsigned int q = 2; (q < params.size()) && (q < 64); q++)
1156                                                 modelist[q] = params_to_keep[n++].c_str();
1157
1158                                 if (smode)
1159                                 {
1160                                         Srv->SendMode(modelist, n+2, who);
1161                                 }
1162                                 else
1163                                 {
1164                                         Srv->CallCommandHandler("MODE", modelist, n+2, who);
1165                                 }
1166
1167                                 /* HOT POTATO! PASS IT ON! */
1168                                 DoOneToAllButSender(source,"FMODE",params,sourceserv);
1169                         }
1170                 }
1171                 else
1172                 /* U-lined servers always win regardless of their TS */
1173                 if ((TS > ourTS) && (!Srv->IsUlined(source)))
1174                 {
1175                         /* Bounce the mode back to its sender.* We use our lower TS, so the other end
1176                          * SHOULD accept it, if its clock is right.
1177                          *
1178                          * NOTE: We should check that we arent bouncing anything thats already set at this end.
1179                          * If we are, bounce +ourmode to 'reinforce' it. This prevents desyncs.
1180                          * e.g. They send +l 50, we have +l 10 set. rather than bounce -l 50, we bounce +l 10.
1181                          *
1182                          * Thanks to jilles for pointing out this one-hell-of-an-issue before i even finished
1183                          * writing the code. It took me a while to come up with this solution.
1184                          *
1185                          * XXX: BE SURE YOU UNDERSTAND THIS CODE FULLY BEFORE YOU MESS WITH IT.
1186                          */
1187
1188                         std::deque<std::string> newparams;      /* New parameter list we send back */
1189                         newparams.push_back(params[0]);         /* Target, user or channel */
1190                         newparams.push_back(ConvToStr(ourTS));  /* Timestamp value of the target */
1191                         newparams.push_back("");                /* This contains the mode string. For now
1192                                                                  * it's empty, we fill it below.
1193                                                                  */
1194
1195                         /* Intelligent mode bouncing. Don't just invert, reinforce any modes which are already
1196                          * set to avoid a desync here.
1197                          */
1198                         std::string modebounce = "";
1199                         bool adding = true;
1200                         unsigned int t = 3;
1201                         ModeHandler* mh = NULL;
1202                         char cur_change = 1;
1203                         char old_change = 0;
1204                         for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
1205                         {
1206                                 /* Iterate over all mode chars in the sent set */
1207                                 switch (*x)
1208                                 {
1209                                         /* Adding or subtracting modes? */
1210                                         case '-':
1211                                                 adding = false;
1212                                         break;
1213                                         case '+':
1214                                                 adding = true;
1215                                         break;
1216                                         default:
1217                                                 /* Find the mode handler for this mode */
1218                                                 mh = ServerInstance->ModeGrok->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1219
1220                                                 /* Got a mode handler?
1221                                                  * This also prevents us bouncing modes we have no handler for.
1222                                                  */
1223                                                 if (mh)
1224                                                 {
1225                                                         ModePair ret;
1226                                                         std::string p = "";
1227
1228                                                         /* Does the mode require a parameter right now?
1229                                                          * If it does, fetch it if we can
1230                                                          */
1231                                                         if ((mh->GetNumParams(adding) > 0) && (t < params.size()))
1232                                                                 p = params[t++];
1233
1234                                                         /* Call the ModeSet method to determine if its set with the
1235                                                          * given parameter here or not.
1236                                                          */
1237                                                         ret = mh->ModeSet(smode ? NULL : who, dst, chan, p);
1238
1239                                                         /* XXX: Really. Dont ask.
1240                                                          * Determine from if its set combined with what the current
1241                                                          * 'state' is (adding or not) as to wether we should 'invert'
1242                                                          * or 'reinforce' the mode change
1243                                                          */
1244                                                         (!ret.first ? (adding ? cur_change = '-' : cur_change = '+') : (!adding ? cur_change = '-' : cur_change = '+'));
1245
1246                                                         /* Quickly determine if we have 'flipped' from + to -,
1247                                                          * or - to +, to prevent unneccessary +/- chars in the
1248                                                          * output string that waste bandwidth
1249                                                          */
1250                                                         if (cur_change != old_change)
1251                                                                 modebounce += cur_change;
1252                                                         old_change = cur_change;
1253
1254                                                         /* Add the mode character to the output string */
1255                                                         modebounce += mh->GetModeChar();
1256
1257                                                         /* We got a parameter back from ModeHandler::ModeSet,
1258                                                          * are we supposed to be sending one out right now?
1259                                                          */
1260                                                         if (ret.second.length())
1261                                                         {
1262                                                                 if (mh->GetNumParams(cur_change == '+') > 0)
1263                                                                         /* Yes we're supposed to be sending out
1264                                                                          * the parameter. Make sure it goes
1265                                                                          */
1266                                                                         newparams.push_back(ret.second);
1267                                                         }
1268
1269                                                 }
1270                                         break;
1271                                 }
1272                         }
1273                         
1274                         /* Update the parameters for FMODE with the new 'bounced' string */
1275                         newparams[2] = modebounce;
1276                         /* Only send it back the way it came, no need to send it anywhere else */
1277                         DoOneToOne(Srv->GetServerName(),"FMODE",newparams,sourceserv);
1278                         log(DEBUG,"FMODE bounced intelligently, our TS less than theirs and the other server is NOT a uline.");
1279                 }
1280                 else
1281                 {
1282                         log(DEBUG,"Allow modes, TS lower for sender");
1283                         /* The server was ulined, but something iffy is up with the TS.
1284                          * Sound the alarm bells!
1285                          */
1286                         if ((Srv->IsUlined(sourceserv)) && (TS > ourTS))
1287                         {
1288                                 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());
1289                         }
1290                         /* Allow the mode, route it to either server or user command handling */
1291                         if (smode)
1292                                 Srv->SendMode(modelist,n,who);
1293                         else
1294                                 Srv->CallCommandHandler("MODE", modelist, n, who);
1295
1296                         /* HOT POTATO! PASS IT ON! */
1297                         DoOneToAllButSender(source,"FMODE",params,sourceserv);
1298                 }
1299                 /* Are we supposed to free the userrec? */
1300                 if (smode)
1301                         DELETE(who);
1302
1303                 return true;
1304         }
1305
1306         /* FTOPIC command */
1307         bool ForceTopic(std::string source, std::deque<std::string> &params)
1308         {
1309                 if (params.size() != 4)
1310                         return true;
1311                 time_t ts = atoi(params[1].c_str());
1312                 std::string nsource = source;
1313
1314                 chanrec* c = Srv->FindChannel(params[0]);
1315                 if (c)
1316                 {
1317                         if ((ts >= c->topicset) || (!*c->topic))
1318                         {
1319                                 std::string oldtopic = c->topic;
1320                                 strlcpy(c->topic,params[3].c_str(),MAXTOPIC);
1321                                 strlcpy(c->setby,params[2].c_str(),NICKMAX-1);
1322                                 c->topicset = ts;
1323                                 /* if the topic text is the same as the current topic,
1324                                  * dont bother to send the TOPIC command out, just silently
1325                                  * update the set time and set nick.
1326                                  */
1327                                 if (oldtopic != params[3])
1328                                 {
1329                                         userrec* user = Srv->FindNick(source);
1330                                         if (!user)
1331                                         {
1332                                                 WriteChannelWithServ(source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
1333                                         }
1334                                         else
1335                                         {
1336                                                 WriteChannel(c, user, "TOPIC %s :%s", c->name, c->topic);
1337                                                 nsource = user->server;
1338                                         }
1339                                         /* all done, send it on its way */
1340                                         params[3] = ":" + params[3];
1341                                         DoOneToAllButSender(source,"FTOPIC",params,nsource);
1342                                 }
1343                         }
1344                         
1345                 }
1346
1347                 return true;
1348         }
1349
1350         /* FJOIN, similar to unreal SJOIN */
1351         bool ForceJoin(std::string source, std::deque<std::string> &params)
1352         {
1353                 if (params.size() < 3)
1354                         return true;
1355
1356                 char first[MAXBUF];
1357                 char modestring[MAXBUF];
1358                 char* mode_users[127];
1359                 memset(&mode_users,0,sizeof(mode_users));
1360                 mode_users[0] = first;
1361                 mode_users[1] = modestring;
1362                 strcpy(first,"+");
1363                 unsigned int modectr = 2;
1364                 
1365                 userrec* who = NULL;
1366                 std::string channel = params[0];
1367                 time_t TS = atoi(params[1].c_str());
1368                 char* key = "";
1369                 
1370                 chanrec* chan = Srv->FindChannel(channel);
1371                 if (chan)
1372                 {
1373                         key = chan->key;
1374                 }
1375                 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
1376
1377                 /* default is a high value, which if we dont have this
1378                  * channel will let the other side apply their modes.
1379                  */
1380                 time_t ourTS = time(NULL)+600;
1381                 chanrec* us = Srv->FindChannel(channel);
1382                 if (us)
1383                 {
1384                         ourTS = us->age;
1385                 }
1386
1387                 log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
1388
1389                 /* do this first, so our mode reversals are correctly received by other servers
1390                  * if there is a TS collision.
1391                  */
1392                 DoOneToAllButSender(source,"FJOIN",params,source);
1393                 
1394                 for (unsigned int usernum = 2; usernum < params.size(); usernum++)
1395                 {
1396                         /* process one channel at a time, applying modes. */
1397                         char* usr = (char*)params[usernum].c_str();
1398                         /* Safety check just to make sure someones not sent us an FJOIN full of spaces
1399                          * (is this even possible?) */
1400                         if (usr && *usr)
1401                         {
1402                                 char permissions = *usr;
1403                                 switch (permissions)
1404                                 {
1405                                         case '@':
1406                                                 usr++;
1407                                                 mode_users[modectr++] = usr;
1408                                                 strlcat(modestring,"o",MAXBUF);
1409                                         break;
1410                                         case '%':
1411                                                 usr++;
1412                                                 mode_users[modectr++] = usr;
1413                                                 strlcat(modestring,"h",MAXBUF);
1414                                         break;
1415                                         case '+':
1416                                                 usr++;
1417                                                 mode_users[modectr++] = usr;
1418                                                 strlcat(modestring,"v",MAXBUF);
1419                                         break;
1420                                 }
1421                                 who = Srv->FindNick(usr);
1422                                 if (who)
1423                                 {
1424                                         Srv->JoinUserToChannel(who,channel,key);
1425                                         if (modectr >= (MAXMODES-1))
1426                                         {
1427                                                 /* theres a mode for this user. push them onto the mode queue, and flush it
1428                                                  * if there are more than MAXMODES to go.
1429                                                  */
1430                                                 if ((ourTS >= TS) || (Srv->IsUlined(who->server)))
1431                                                 {
1432                                                         /* We also always let u-lined clients win, no matter what the TS value */
1433                                                         log(DEBUG,"Our our channel newer than theirs, accepting their modes");
1434                                                         Srv->SendMode((const char**)mode_users,modectr,who);
1435                                                         if (ourTS != TS)
1436                                                         {
1437                                                                 log(DEFAULT,"Channel TS for %s changed from %lu to %lu",us,ourTS,TS);
1438                                                                 us->age = TS;
1439                                                         }
1440                                                 }
1441                                                 else
1442                                                 {
1443                                                         log(DEBUG,"Their channel newer than ours, bouncing their modes");
1444                                                         /* bouncy bouncy! */
1445                                                         std::deque<std::string> params;
1446                                                         /* modes are now being UNSET... */
1447                                                         *mode_users[1] = '-';
1448                                                         for (unsigned int x = 0; x < modectr; x++)
1449                                                         {
1450                                                                 if (x == 1)
1451                                                                 {
1452                                                                         params.push_back(ConvToStr(us->age));
1453                                                                 }
1454                                                                 params.push_back(mode_users[x]);
1455                                                         }
1456                                                         // tell everyone to bounce the modes. bad modes, bad!
1457                                                         DoOneToMany(Srv->GetServerName(),"FMODE",params);
1458                                                 }
1459                                                 strcpy(mode_users[1],"+");
1460                                                 modectr = 2;
1461                                         }
1462                                 }
1463                         }
1464                 }
1465                 /* there werent enough modes built up to flush it during FJOIN,
1466                  * or, there are a number left over. flush them out.
1467                  */
1468                 if ((modectr > 2) && (who))
1469                 {
1470                         if (ourTS >= TS)
1471                         {
1472                                 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
1473                                 Srv->SendMode((const char**)mode_users,modectr,who);
1474                                 if (ourTS != TS)
1475                                 {
1476                                         log(DEFAULT,"Channel TS for %s changed from %lu to %lu",us,ourTS,TS);
1477                                         us->age = TS;
1478                                 }
1479                         }
1480                         else
1481                         {
1482                                 log(DEBUG,"Their channel newer than ours, bouncing their modes");
1483                                 std::deque<std::string> params;
1484                                 *mode_users[1] = '-';
1485                                 for (unsigned int x = 0; x < modectr; x++)
1486                                 {
1487                                         if (x == 1)
1488                                         {
1489                                                 params.push_back(ConvToStr(us->age));
1490                                         }
1491                                         params.push_back(mode_users[x]);
1492                                 }
1493                                 DoOneToMany(Srv->GetServerName(),"FMODE",params);
1494                         }
1495                 }
1496                 return true;
1497         }
1498
1499         bool SyncChannelTS(std::string source, std::deque<std::string> &params)
1500         {
1501                 if (params.size() >= 2)
1502                 {
1503                         chanrec* c = Srv->FindChannel(params[0]);
1504                         if (c)
1505                         {
1506                                 time_t theirTS = atoi(params[1].c_str());
1507                                 time_t ourTS = c->age;
1508                                 if (ourTS >= theirTS)
1509                                 {
1510                                         log(DEBUG,"Updating timestamp for %s, our timestamp was %lu and theirs is %lu",c->name,ourTS,theirTS);
1511                                         c->age = theirTS;
1512                                 }
1513                         }
1514                 }
1515                 DoOneToAllButSender(Srv->GetServerName(),"SYNCTS",params,source);
1516                 return true;
1517         }
1518
1519         /* NICK command */
1520         bool IntroduceClient(std::string source, std::deque<std::string> &params)
1521         {
1522                 if (params.size() < 8)
1523                         return true;
1524                 if (params.size() > 8)
1525                 {
1526                         this->WriteLine(":"+Srv->GetServerName()+" KILL "+params[1]+" :Invalid client introduction ("+params[1]+"?)");
1527                         return true;
1528                 }
1529                 // NICK age nick host dhost ident +modes ip :gecos
1530                 //       0    1   2     3     4      5   6     7
1531                 time_t age = atoi(params[0].c_str());
1532                 
1533                 /* This used to have a pretty craq'y loop doing the same thing,
1534                  * now we just let the STL do the hard work (more efficiently)
1535                  */
1536                 params[5] = params[5].substr(params[5].find_first_not_of('+'));
1537                 
1538                 const char* tempnick = params[1].c_str();
1539                 log(DEBUG,"Introduce client %s!%s@%s",tempnick,params[4].c_str(),params[2].c_str());
1540                 
1541                 user_hash::iterator iter = clientlist.find(tempnick);
1542                 
1543                 if (iter != clientlist.end())
1544                 {
1545                         // nick collision
1546                         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);
1547                         this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
1548                         return true;
1549                 }
1550
1551                 clientlist[tempnick] = new userrec();
1552                 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
1553                 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX-1);
1554                 strlcpy(clientlist[tempnick]->host, params[2].c_str(),63);
1555                 strlcpy(clientlist[tempnick]->dhost, params[3].c_str(),63);
1556                 clientlist[tempnick]->server = FindServerNamePtr(source.c_str());
1557                 strlcpy(clientlist[tempnick]->ident, params[4].c_str(),IDENTMAX);
1558                 strlcpy(clientlist[tempnick]->fullname, params[7].c_str(),MAXGECOS);
1559                 clientlist[tempnick]->registered = REG_ALL;
1560                 clientlist[tempnick]->signon = age;
1561                 
1562                 for (std::string::iterator v = params[5].begin(); v != params[5].end(); v++)
1563                 {
1564                         clientlist[tempnick]->modes[(*v)-65] = 1;
1565                 }
1566
1567                 if (params[6].find_first_of(":") != std::string::npos)
1568                         clientlist[tempnick]->SetSockAddr(AF_INET6, params[6].c_str(), 0);
1569                 else
1570                         clientlist[tempnick]->SetSockAddr(AF_INET, params[6].c_str(), 0);
1571
1572                 WriteOpers("*** Client connecting at %s: %s!%s@%s [%s]",clientlist[tempnick]->server,clientlist[tempnick]->nick,clientlist[tempnick]->ident,clientlist[tempnick]->host, clientlist[tempnick]->GetIPString());
1573
1574                 params[7] = ":" + params[7];
1575                 DoOneToAllButSender(source,"NICK",params,source);
1576
1577                 // Increment the Source Servers User Count..
1578                 TreeServer* SourceServer = FindServer(source);
1579                 if (SourceServer)
1580                 {
1581                         log(DEBUG,"Found source server of %s",clientlist[tempnick]->nick);
1582                         SourceServer->AddUserCount();
1583                 }
1584
1585                 return true;
1586         }
1587
1588         /* Send one or more FJOINs for a channel of users.
1589          * If the length of a single line is more than 480-NICKMAX
1590          * in length, it is split over multiple lines.
1591          */
1592         void SendFJoins(TreeServer* Current, chanrec* c)
1593         {
1594                 log(DEBUG,"Sending FJOINs to other server for %s",c->name);
1595                 char list[MAXBUF];
1596                 std::string individual_halfops = ":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age);
1597                 
1598                 size_t dlen, curlen;
1599                 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1600                 int numusers = 0;
1601                 char* ptr = list + dlen;
1602
1603                 CUList *ulist = c->GetUsers();
1604                 std::vector<userrec*> specific_halfop;
1605                 std::vector<userrec*> specific_voice;
1606                 std::string modes = "";
1607                 std::string params = "";
1608
1609                 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1610                 {
1611                         int x = cflags(i->second,c);
1612                         if ((x & UCMODE_HOP) && (x & UCMODE_OP))
1613                         {
1614                                 specific_halfop.push_back(i->second);
1615                         }
1616                         if (((x & UCMODE_HOP) || (x & UCMODE_OP)) && (x & UCMODE_VOICE))
1617                         {
1618                                 specific_voice.push_back(i->second);
1619                         }
1620
1621                         const char* n = "";
1622                         if (x & UCMODE_OP)
1623                         {
1624                                 n = "@";
1625                         }
1626                         else if (x & UCMODE_HOP)
1627                         {
1628                                 n = "%";
1629                         }
1630                         else if (x & UCMODE_VOICE)
1631                         {
1632                                 n = "+";
1633                         }
1634
1635                         size_t ptrlen = snprintf(ptr, MAXBUF, " %s%s", n, i->second->nick);
1636
1637                         curlen += ptrlen;
1638                         ptr += ptrlen;
1639
1640                         numusers++;
1641
1642                         if (curlen > (480-NICKMAX))
1643                         {
1644                                 this->WriteLine(list);
1645                                 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1646                                 ptr = list + dlen;
1647                                 ptrlen = 0;
1648                                 numusers = 0;
1649                                 for (unsigned int y = 0; y < specific_voice.size(); y++)
1650                                 {
1651                                         modes.append("v");
1652                                         params.append(specific_voice[y]->nick).append(" ");
1653                                         //this->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" +v "+specific_voice[y]->nick);
1654                                 }
1655                                 for (unsigned int y = 0; y < specific_halfop.size(); y++)
1656                                 {
1657                                         modes.append("h");
1658                                         params.append(specific_halfop[y]->nick).append(" ");
1659                                         //this->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" +h "+specific_halfop[y]->nick);
1660                                 }
1661                         }
1662                 }
1663                 if (numusers)
1664                 {
1665                         this->WriteLine(list);
1666                         for (unsigned int y = 0; y < specific_voice.size(); y++)
1667                         {
1668                                 modes.append("v");
1669                                 params.append(specific_voice[y]->nick).append(" ");
1670                                 //this->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" +v "+specific_voice[y]->nick);
1671                         }
1672                         for (unsigned int y = 0; y < specific_halfop.size(); y++)
1673                         {
1674                                 modes.append("h");
1675                                 params.append(specific_halfop[y]->nick).append(" ");
1676                                 //this->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" +h "+specific_halfop[y]->nick);
1677                         }
1678                 }
1679                 //std::string modes = "";
1680                 //std::string params = "";
1681                 for (BanList::iterator b = c->bans.begin(); b != c->bans.end(); b++)
1682                 {
1683                         modes.append("b");
1684                         params.append(b->data).append(" ");
1685                 }
1686                 /* XXX: Send each channel mode and its params -- we'll need a method for this in ModeHandler? */
1687                 //FOREACH_MOD(I_OnSyncChannel,OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this));
1688                 this->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" +"+chanmodes(c,true)+modes+" "+params);
1689         }
1690
1691         /* Send G, Q, Z and E lines */
1692         void SendXLines(TreeServer* Current)
1693         {
1694                 char data[MAXBUF];
1695                 std::string n = Srv->GetServerName();
1696                 const char* sn = n.c_str();
1697                 int iterations = 0;
1698                 /* Yes, these arent too nice looking, but they get the job done */
1699                 for (std::vector<ZLine>::iterator i = zlines.begin(); i != zlines.end(); i++, iterations++)
1700                 {
1701                         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);
1702                         this->WriteLine(data);
1703                 }
1704                 for (std::vector<QLine>::iterator i = qlines.begin(); i != qlines.end(); i++, iterations++)
1705                 {
1706                         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);
1707                         this->WriteLine(data);
1708                 }
1709                 for (std::vector<GLine>::iterator i = glines.begin(); i != glines.end(); i++, iterations++)
1710                 {
1711                         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);
1712                         this->WriteLine(data);
1713                 }
1714                 for (std::vector<ELine>::iterator i = elines.begin(); i != elines.end(); i++, iterations++)
1715                 {
1716                         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);
1717                         this->WriteLine(data);
1718                 }
1719                 for (std::vector<ZLine>::iterator i = pzlines.begin(); i != pzlines.end(); i++, iterations++)
1720                 {
1721                         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);
1722                         this->WriteLine(data);
1723                 }
1724                 for (std::vector<QLine>::iterator i = pqlines.begin(); i != pqlines.end(); i++, iterations++)
1725                 {
1726                         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);
1727                         this->WriteLine(data);
1728                 }
1729                 for (std::vector<GLine>::iterator i = pglines.begin(); i != pglines.end(); i++, iterations++)
1730                 {
1731                         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);
1732                         this->WriteLine(data);
1733                 }
1734                 for (std::vector<ELine>::iterator i = pelines.begin(); i != pelines.end(); i++, iterations++)
1735                 {
1736                         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);
1737                         this->WriteLine(data);
1738                 }
1739         }
1740
1741         /* Send channel modes and topics */
1742         void SendChannelModes(TreeServer* Current)
1743         {
1744                 char data[MAXBUF];
1745                 std::deque<std::string> list;
1746                 int iterations = 0;
1747                 std::string n = Srv->GetServerName();
1748                 const char* sn = n.c_str();
1749                 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++, iterations++)
1750                 {
1751                         SendFJoins(Current, c->second);
1752                         if (*c->second->topic)
1753                         {
1754                                 snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",sn,c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
1755                                 this->WriteLine(data);
1756                         }
1757                         FOREACH_MOD(I_OnSyncChannel,OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this));
1758                         list.clear();
1759                         c->second->GetExtList(list);
1760                         for (unsigned int j = 0; j < list.size(); j++)
1761                         {
1762                                 FOREACH_MOD(I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
1763                         }
1764                 }
1765         }
1766
1767         /* send all users and their oper state/modes */
1768         void SendUsers(TreeServer* Current)
1769         {
1770                 char data[MAXBUF];
1771                 std::deque<std::string> list;
1772                 int iterations = 0;
1773                 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++, iterations++)
1774                 {
1775                         if (u->second->registered == REG_ALL)
1776                         {
1777                                 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);
1778                                 this->WriteLine(data);
1779                                 if (*u->second->oper)
1780                                 {
1781                                         this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
1782                                 }
1783                                 if (*u->second->awaymsg)
1784                                 {
1785                                         this->WriteLine(":"+std::string(u->second->nick)+" AWAY :"+std::string(u->second->awaymsg));
1786                                 }
1787                                 FOREACH_MOD(I_OnSyncUser,OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this));
1788                                 list.clear();
1789                                 u->second->GetExtList(list);
1790                                 for (unsigned int j = 0; j < list.size(); j++)
1791                                 {
1792                                         FOREACH_MOD(I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
1793                                 }
1794                         }
1795                 }
1796         }
1797
1798         /* This function is called when we want to send a netburst to a local
1799          * server. There is a set order we must do this, because for example
1800          * users require their servers to exist, and channels require their
1801          * users to exist. You get the idea.
1802          */
1803         void DoBurst(TreeServer* s)
1804         {
1805                 /* The calls here to ServerInstance-> yield the processing
1806                  * back to the core so that a large burst is split into at least 6 sections
1807                  * (possibly more)
1808                  */
1809                 std::string burst = "BURST "+ConvToStr(time(NULL));
1810                 std::string endburst = "ENDBURST";
1811                 // Because by the end of the netburst, it  could be gone!
1812                 std::string name = s->GetName();
1813                 Srv->SendOpers("*** Bursting to \2"+name+"\2.");
1814                 this->WriteLine(burst);
1815                 /* send our version string */
1816                 this->WriteLine(":"+Srv->GetServerName()+" VERSION :"+Srv->GetVersion());
1817                 /* Send server tree */
1818                 this->SendServers(TreeRoot,s,1);
1819                 /* Send users and their oper status */
1820                 this->SendUsers(s);
1821                 /* Send everything else (channel modes, xlines etc) */
1822                 this->SendChannelModes(s);
1823                 this->SendXLines(s);            
1824                 FOREACH_MOD(I_OnSyncOtherMetaData,OnSyncOtherMetaData((Module*)TreeProtocolModule,(void*)this));
1825                 this->WriteLine(endburst);
1826                 Srv->SendOpers("*** Finished bursting to \2"+name+"\2.");
1827         }
1828
1829         /* This function is called when we receive data from a remote
1830          * server. We buffer the data in a std::string (it doesnt stay
1831          * there for long), reading using InspSocket::Read() which can
1832          * read up to 16 kilobytes in one operation.
1833          *
1834          * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
1835          * THE SOCKET OBJECT FOR US.
1836          */
1837         virtual bool OnDataReady()
1838         {
1839                 char* data = this->Read();
1840                 /* Check that the data read is a valid pointer and it has some content */
1841                 if (data && *data)
1842                 {
1843                         this->in_buffer.append(data);
1844                         /* While there is at least one new line in the buffer,
1845                          * do something useful (we hope!) with it.
1846                          */
1847                         while (in_buffer.find("\n") != std::string::npos)
1848                         {
1849                                 std::string ret = in_buffer.substr(0,in_buffer.find("\n")-1);
1850                                 in_buffer = in_buffer.substr(in_buffer.find("\n")+1,in_buffer.length()-in_buffer.find("\n"));
1851                                 if (ret.find("\r") != std::string::npos)
1852                                         ret = in_buffer.substr(0,in_buffer.find("\r")-1);
1853                                 /* Process this one, abort if it
1854                                  * didnt return true.
1855                                  */
1856                                 if (this->ctx_in)
1857                                 {
1858                                         char out[1024];
1859                                         char result[1024];
1860                                         memset(result,0,1024);
1861                                         memset(out,0,1024);
1862                                         log(DEBUG,"Original string '%s'",ret.c_str());
1863                                         /* ERROR + CAPAB is still allowed unencryped */
1864                                         if ((ret.substr(0,7) != "ERROR :") && (ret.substr(0,6) != "CAPAB "))
1865                                         {
1866                                                 int nbytes = from64tobits(out, ret.c_str(), 1024);
1867                                                 if ((nbytes > 0) && (nbytes < 1024))
1868                                                 {
1869                                                         log(DEBUG,"m_spanningtree: decrypt %d bytes",nbytes);
1870                                                         ctx_in->Decrypt(out, result, nbytes, 0);
1871                                                         for (int t = 0; t < nbytes; t++)
1872                                                                 if (result[t] == '\7') result[t] = 0;
1873                                                         ret = result;
1874                                                 }
1875                                         }
1876                                 }
1877                                 if (!this->ProcessLine(ret))
1878                                 {
1879                                         log(DEBUG,"ProcessLine says no!");
1880                                         return false;
1881                                 }
1882                         }
1883                         return true;
1884                 }
1885                 /* EAGAIN returns an empty but non-NULL string, so this
1886                  * evaluates to TRUE for EAGAIN but to FALSE for EOF.
1887                  */
1888                 return (data && !*data);
1889         }
1890
1891         int WriteLine(std::string line)
1892         {
1893                 log(DEBUG,"OUT: %s",line.c_str());
1894                 if (this->ctx_out)
1895                 {
1896                         char result[10240];
1897                         char result64[10240];
1898                         if (this->keylength)
1899                         {
1900                                 // pad it to the key length
1901                                 int n = this->keylength - (line.length() % this->keylength);
1902                                 if (n)
1903                                 {
1904                                         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);
1905                                         line.append(n,'\7');
1906                                 }
1907                         }
1908                         unsigned int ll = line.length();
1909                         ctx_out->Encrypt(line.c_str(), result, ll, 0);
1910                         to64frombits((unsigned char*)result64,(unsigned char*)result,ll);
1911                         line = result64;
1912                         //int from64tobits(char *out, const char *in, int maxlen);
1913                 }
1914                 return this->Write(line + "\r\n");
1915         }
1916
1917         /* Handle ERROR command */
1918         bool Error(std::deque<std::string> &params)
1919         {
1920                 if (params.size() < 1)
1921                         return false;
1922                 WriteOpers("*** ERROR from %s: %s",(InboundServerName != "" ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
1923                 /* we will return false to cause the socket to close. */
1924                 return false;
1925         }
1926
1927         bool Stats(std::string prefix, std::deque<std::string> &params)
1928         {
1929                 /* Get the reply to a STATS query if it matches this servername,
1930                  * and send it back as a load of PUSH queries
1931                  */
1932                 if (params.size() > 1)
1933                 {
1934                         if (Srv->MatchText(Srv->GetServerName(), params[1]))
1935                         {
1936                                 /* It's for our server */
1937                                 string_list results;
1938                                 userrec* source = Srv->FindNick(prefix);
1939                                 if (source)
1940                                 {
1941                                         std::deque<std::string> par;
1942                                         par.push_back(prefix);
1943                                         par.push_back("");
1944                                         DoStats(*(params[0].c_str()), source, results);
1945                                         for (size_t i = 0; i < results.size(); i++)
1946                                         {
1947                                                 par[1] = "::" + results[i];
1948                                                 DoOneToOne(Srv->GetServerName(), "PUSH",par, source->server);
1949                                         }
1950                                 }
1951                         }
1952                         else
1953                         {
1954                                 /* Pass it on */
1955                                 userrec* source = Srv->FindNick(prefix);
1956                                 if (source)
1957                                         DoOneToOne(prefix, "STATS", params, params[1]);
1958                         }
1959                 }
1960                 return true;
1961         }
1962
1963
1964         /* Because the core won't let users or even SERVERS set +o,
1965          * we use the OPERTYPE command to do this.
1966          */
1967         bool OperType(std::string prefix, std::deque<std::string> &params)
1968         {
1969                 if (params.size() != 1)
1970                 {
1971                         log(DEBUG,"Received invalid oper type from %s",prefix.c_str());
1972                         return true;
1973                 }
1974                 std::string opertype = params[0];
1975                 userrec* u = Srv->FindNick(prefix);
1976                 if (u)
1977                 {
1978                         u->modes[UM_OPERATOR] = 1;
1979                         strlcpy(u->oper,opertype.c_str(),NICKMAX-1);
1980                         DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
1981                 }
1982                 return true;
1983         }
1984
1985         /* Because Andy insists that services-compatible servers must
1986          * implement SVSNICK and SVSJOIN, that's exactly what we do :p
1987          */
1988         bool ForceNick(std::string prefix, std::deque<std::string> &params)
1989         {
1990                 if (params.size() < 3)
1991                         return true;
1992
1993                 userrec* u = Srv->FindNick(params[0]);
1994
1995                 if (u)
1996                 {
1997                         DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
1998                         if (IS_LOCAL(u))
1999                         {
2000                                 std::deque<std::string> par;
2001                                 par.push_back(params[1]);
2002                                 /* This is not required as one is sent in OnUserPostNick below
2003                                  */
2004                                 //DoOneToMany(u->nick,"NICK",par);
2005                                 Srv->ChangeUserNick(u,params[1]);
2006                                 u->age = atoi(params[2].c_str());
2007                         }
2008                 }
2009                 return true;
2010         }
2011
2012         bool ServiceJoin(std::string prefix, std::deque<std::string> &params)
2013         {
2014                 if (params.size() < 2)
2015                         return true;
2016
2017                 userrec* u = Srv->FindNick(params[0]);
2018
2019                 if (u)
2020                 {
2021                         Srv->JoinUserToChannel(u,params[1],"");
2022                         DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
2023                 }
2024                 return true;
2025         }
2026
2027         bool RemoteRehash(std::string prefix, std::deque<std::string> &params)
2028         {
2029                 if (params.size() < 1)
2030                         return false;
2031
2032                 std::string servermask = params[0];
2033
2034                 if (Srv->MatchText(Srv->GetServerName(),servermask))
2035                 {
2036                         Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
2037                         Srv->RehashServer();
2038                         ReadConfiguration(false);
2039                 }
2040                 DoOneToAllButSender(prefix,"REHASH",params,prefix);
2041                 return true;
2042         }
2043
2044         bool RemoteKill(std::string prefix, std::deque<std::string> &params)
2045         {
2046                 if (params.size() != 2)
2047                         return true;
2048
2049                 std::string nick = params[0];
2050                 userrec* u = Srv->FindNick(prefix);
2051                 userrec* who = Srv->FindNick(nick);
2052
2053                 if (who)
2054                 {
2055                         /* Prepend kill source, if we don't have one */
2056                         std::string sourceserv = prefix;
2057                         if (u)
2058                         {
2059                                 sourceserv = u->server;
2060                         }
2061                         if (*(params[1].c_str()) != '[')
2062                         {
2063                                 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
2064                         }
2065                         std::string reason = params[1];
2066                         params[1] = ":" + params[1];
2067                         DoOneToAllButSender(prefix,"KILL",params,sourceserv);
2068                         ::Write(who->fd, ":%s KILL %s :%s (%s)", sourceserv.c_str(), who->nick, sourceserv.c_str(), reason.c_str());
2069                         Srv->QuitUser(who,reason);
2070                 }
2071                 return true;
2072         }
2073
2074         bool LocalPong(std::string prefix, std::deque<std::string> &params)
2075         {
2076                 if (params.size() < 1)
2077                         return true;
2078
2079                 if (params.size() == 1)
2080                 {
2081                         TreeServer* ServerSource = FindServer(prefix);
2082                         if (ServerSource)
2083                         {
2084                                 ServerSource->SetPingFlag();
2085                         }
2086                 }
2087                 else
2088                 {
2089                         std::string forwardto = params[1];
2090                         if (forwardto == Srv->GetServerName())
2091                         {
2092                                 /*
2093                                  * this is a PONG for us
2094                                  * if the prefix is a user, check theyre local, and if they are,
2095                                  * dump the PONG reply back to their fd. If its a server, do nowt.
2096                                  * Services might want to send these s->s, but we dont need to yet.
2097                                  */
2098                                 userrec* u = Srv->FindNick(prefix);
2099
2100                                 if (u)
2101                                 {
2102                                         WriteServ(u->fd,"PONG %s %s",params[0].c_str(),params[1].c_str());
2103                                 }
2104                         }
2105                         else
2106                         {
2107                                 // not for us, pass it on :)
2108                                 DoOneToOne(prefix,"PONG",params,forwardto);
2109                         }
2110                 }
2111
2112                 return true;
2113         }
2114         
2115         bool MetaData(std::string prefix, std::deque<std::string> &params)
2116         {
2117                 if (params.size() < 3)
2118                         return true;
2119
2120                 TreeServer* ServerSource = FindServer(prefix);
2121
2122                 if (ServerSource)
2123                 {
2124                         if (params[0] == "*")
2125                         {
2126                                 FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
2127                         }
2128                         else if (*(params[0].c_str()) == '#')
2129                         {
2130                                 chanrec* c = Srv->FindChannel(params[0]);
2131                                 if (c)
2132                                 {
2133                                         FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
2134                                 }
2135                         }
2136                         else if (*(params[0].c_str()) != '#')
2137                         {
2138                                 userrec* u = Srv->FindNick(params[0]);
2139                                 if (u)
2140                                 {
2141                                         FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
2142                                 }
2143                         }
2144                 }
2145
2146                 params[2] = ":" + params[2];
2147                 DoOneToAllButSender(prefix,"METADATA",params,prefix);
2148                 return true;
2149         }
2150
2151         bool ServerVersion(std::string prefix, std::deque<std::string> &params)
2152         {
2153                 if (params.size() < 1)
2154                         return true;
2155
2156                 TreeServer* ServerSource = FindServer(prefix);
2157
2158                 if (ServerSource)
2159                 {
2160                         ServerSource->SetVersion(params[0]);
2161                 }
2162                 params[0] = ":" + params[0];
2163                 DoOneToAllButSender(prefix,"VERSION",params,prefix);
2164                 return true;
2165         }
2166
2167         bool ChangeHost(std::string prefix, std::deque<std::string> &params)
2168         {
2169                 if (params.size() < 1)
2170                         return true;
2171
2172                 userrec* u = Srv->FindNick(prefix);
2173
2174                 if (u)
2175                 {
2176                         Srv->ChangeHost(u,params[0]);
2177                         DoOneToAllButSender(prefix,"FHOST",params,u->server);
2178                 }
2179                 return true;
2180         }
2181
2182         bool AddLine(std::string prefix, std::deque<std::string> &params)
2183         {
2184                 if (params.size() < 6)
2185                         return true;
2186
2187                 bool propogate = false;
2188
2189                 switch (*(params[0].c_str()))
2190                 {
2191                         case 'Z':
2192                                 propogate = add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2193                                 zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2194                         break;
2195                         case 'Q':
2196                                 propogate = add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2197                                 qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2198                         break;
2199                         case 'E':
2200                                 propogate = add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2201                                 eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2202                         break;
2203                         case 'G':
2204                                 propogate = add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2205                                 gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2206                         break;
2207                         case 'K':
2208                                 propogate = add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2209                         break;
2210                         default:
2211                                 /* Just in case... */
2212                                 Srv->SendOpers("*** \2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");
2213                                 propogate = false;
2214                         break;
2215                 }
2216
2217                 /* Send it on its way */
2218                 if (propogate)
2219                 {
2220                         if (atoi(params[4].c_str()))
2221                         {
2222                                 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());
2223                         }
2224                         else
2225                         {
2226                                 WriteOpers("*** %s Added permenant %cLINE on %s (%s).",prefix.c_str(),*(params[0].c_str()),params[1].c_str(),params[5].c_str());
2227                         }
2228                         params[5] = ":" + params[5];
2229                         DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
2230                 }
2231                 if (!this->bursting)
2232                 {
2233                         log(DEBUG,"Applying lines...");
2234                         apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2235                 }
2236                 return true;
2237         }
2238
2239         bool ChangeName(std::string prefix, std::deque<std::string> &params)
2240         {
2241                 if (params.size() < 1)
2242                         return true;
2243
2244                 userrec* u = Srv->FindNick(prefix);
2245
2246                 if (u)
2247                 {
2248                         Srv->ChangeGECOS(u,params[0]);
2249                         params[0] = ":" + params[0];
2250                         DoOneToAllButSender(prefix,"FNAME",params,u->server);
2251                 }
2252                 return true;
2253         }
2254
2255         bool Whois(std::string prefix, std::deque<std::string> &params)
2256         {
2257                 if (params.size() < 1)
2258                         return true;
2259
2260                 log(DEBUG,"In IDLE command");
2261                 userrec* u = Srv->FindNick(prefix);
2262
2263                 if (u)
2264                 {
2265                         log(DEBUG,"USER EXISTS: %s",u->nick);
2266                         // an incoming request
2267                         if (params.size() == 1)
2268                         {
2269                                 userrec* x = Srv->FindNick(params[0]);
2270                                 if ((x) && (IS_LOCAL(x)))
2271                                 {
2272                                         userrec* x = Srv->FindNick(params[0]);
2273                                         log(DEBUG,"Got IDLE");
2274                                         char signon[MAXBUF];
2275                                         char idle[MAXBUF];
2276                                         log(DEBUG,"Sending back IDLE 3");
2277                                         snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
2278                                         snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-time(NULL)));
2279                                         std::deque<std::string> par;
2280                                         par.push_back(prefix);
2281                                         par.push_back(signon);
2282                                         par.push_back(idle);
2283                                         // ours, we're done, pass it BACK
2284                                         DoOneToOne(params[0],"IDLE",par,u->server);
2285                                 }
2286                                 else
2287                                 {
2288                                         // not ours pass it on
2289                                         DoOneToOne(prefix,"IDLE",params,x->server);
2290                                 }
2291                         }
2292                         else if (params.size() == 3)
2293                         {
2294                                 std::string who_did_the_whois = params[0];
2295                                 userrec* who_to_send_to = Srv->FindNick(who_did_the_whois);
2296                                 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2297                                 {
2298                                         log(DEBUG,"Got final IDLE");
2299                                         // an incoming reply to a whois we sent out
2300                                         std::string nick_whoised = prefix;
2301                                         unsigned long signon = atoi(params[1].c_str());
2302                                         unsigned long idle = atoi(params[2].c_str());
2303                                         if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2304                                                 do_whois(who_to_send_to,u,signon,idle,nick_whoised.c_str());
2305                                 }
2306                                 else
2307                                 {
2308                                         // not ours, pass it on
2309                                         DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
2310                                 }
2311                         }
2312                 }
2313                 return true;
2314         }
2315
2316         bool Push(std::string prefix, std::deque<std::string> &params)
2317         {
2318                 if (params.size() < 2)
2319                         return true;
2320
2321                 userrec* u = Srv->FindNick(params[0]);
2322
2323                 if (!u)
2324                         return true;
2325
2326                 if (IS_LOCAL(u))
2327                 {
2328                         ::Write(u->fd,"%s",params[1].c_str());
2329                 }
2330                 else
2331                 {
2332                         // continue the raw onwards
2333                         params[1] = ":" + params[1];
2334                         DoOneToOne(prefix,"PUSH",params,u->server);
2335                 }
2336                 return true;
2337         }
2338
2339         bool Time(std::string prefix, std::deque<std::string> &params)
2340         {
2341                 // :source.server TIME remote.server sendernick
2342                 // :remote.server TIME source.server sendernick TS
2343                 if (params.size() == 2)
2344                 {
2345                         // someone querying our time?
2346                         if (Srv->GetServerName() == params[0])
2347                         {
2348                                 userrec* u = Srv->FindNick(params[1]);
2349                                 if (u)
2350                                 {
2351                                         char curtime[256];
2352                                         snprintf(curtime,256,"%lu",(unsigned long)time(NULL));
2353                                         params.push_back(curtime);
2354                                         params[0] = prefix;
2355                                         DoOneToOne(Srv->GetServerName(),"TIME",params,params[0]);
2356                                 }
2357                         }
2358                         else
2359                         {
2360                                 // not us, pass it on
2361                                 userrec* u = Srv->FindNick(params[1]);
2362                                 if (u)
2363                                         DoOneToOne(prefix,"TIME",params,params[0]);
2364                         }
2365                 }
2366                 else if (params.size() == 3)
2367                 {
2368                         // a response to a previous TIME
2369                         userrec* u = Srv->FindNick(params[1]);
2370                         if ((u) && (IS_LOCAL(u)))
2371                         {
2372                         time_t rawtime = atol(params[2].c_str());
2373                         struct tm * timeinfo;
2374                         timeinfo = localtime(&rawtime);
2375                                 char tms[26];
2376                                 snprintf(tms,26,"%s",asctime(timeinfo));
2377                                 tms[24] = 0;
2378                         WriteServ(u->fd,"391 %s %s :%s",u->nick,prefix.c_str(),tms);
2379                         }
2380                         else
2381                         {
2382                                 if (u)
2383                                         DoOneToOne(prefix,"TIME",params,u->server);
2384                         }
2385                 }
2386                 return true;
2387         }
2388         
2389         bool LocalPing(std::string prefix, std::deque<std::string> &params)
2390         {
2391                 if (params.size() < 1)
2392                         return true;
2393
2394                 if (params.size() == 1)
2395                 {
2396                         std::string stufftobounce = params[0];
2397                         this->WriteLine(":"+Srv->GetServerName()+" PONG "+stufftobounce);
2398                         return true;
2399                 }
2400                 else
2401                 {
2402                         std::string forwardto = params[1];
2403                         if (forwardto == Srv->GetServerName())
2404                         {
2405                                 // this is a ping for us, send back PONG to the requesting server
2406                                 params[1] = params[0];
2407                                 params[0] = forwardto;
2408                                 DoOneToOne(forwardto,"PONG",params,params[1]);
2409                         }
2410                         else
2411                         {
2412                                 // not for us, pass it on :)
2413                                 DoOneToOne(prefix,"PING",params,forwardto);
2414                         }
2415                         return true;
2416                 }
2417         }
2418
2419         bool RemoteServer(std::string prefix, std::deque<std::string> &params)
2420         {
2421                 if (params.size() < 4)
2422                         return false;
2423
2424                 std::string servername = params[0];
2425                 std::string password = params[1];
2426                 // hopcount is not used for a remote server, we calculate this ourselves
2427                 std::string description = params[3];
2428                 TreeServer* ParentOfThis = FindServer(prefix);
2429
2430                 if (!ParentOfThis)
2431                 {
2432                         this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
2433                         return false;
2434                 }
2435                 TreeServer* CheckDupe = FindServer(servername);
2436                 if (CheckDupe)
2437                 {
2438                         this->WriteLine("ERROR :Server "+servername+" already exists!");
2439                         Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists");
2440                         return false;
2441                 }
2442                 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
2443                 ParentOfThis->AddChild(Node);
2444                 params[3] = ":" + params[3];
2445                 DoOneToAllButSender(prefix,"SERVER",params,prefix);
2446                 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
2447                 return true;
2448         }
2449
2450         bool Outbound_Reply_Server(std::deque<std::string> &params)
2451         {
2452                 if (params.size() < 4)
2453                         return false;
2454
2455                 irc::string servername = params[0].c_str();
2456                 std::string sname = params[0];
2457                 std::string password = params[1];
2458                 int hops = atoi(params[2].c_str());
2459
2460                 if (hops)
2461                 {
2462                         this->WriteLine("ERROR :Server too far away for authentication");
2463                         Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2464                         return false;
2465                 }
2466                 std::string description = params[3];
2467                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2468                 {
2469                         if ((x->Name == servername) && (x->RecvPass == password))
2470                         {
2471                                 TreeServer* CheckDupe = FindServer(sname);
2472                                 if (CheckDupe)
2473                                 {
2474                                         this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
2475                                         Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
2476                                         return false;
2477                                 }
2478                                 // Begin the sync here. this kickstarts the
2479                                 // other side, waiting in WAIT_AUTH_2 state,
2480                                 // into starting their burst, as it shows
2481                                 // that we're happy.
2482                                 this->LinkState = CONNECTED;
2483                                 // we should add the details of this server now
2484                                 // to the servers tree, as a child of the root
2485                                 // node.
2486                                 TreeServer* Node = new TreeServer(sname,description,TreeRoot,this);
2487                                 TreeRoot->AddChild(Node);
2488                                 params[3] = ":" + params[3];
2489                                 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,sname);
2490                                 this->bursting = true;
2491                                 this->DoBurst(Node);
2492                                 return true;
2493                         }
2494                 }
2495                 this->WriteLine("ERROR :Invalid credentials");
2496                 Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, invalid link credentials");
2497                 return false;
2498         }
2499
2500         bool Inbound_Server(std::deque<std::string> &params)
2501         {
2502                 if (params.size() < 4)
2503                         return false;
2504
2505                 irc::string servername = params[0].c_str();
2506                 std::string sname = params[0];
2507                 std::string password = params[1];
2508                 int hops = atoi(params[2].c_str());
2509
2510                 if (hops)
2511                 {
2512                         this->WriteLine("ERROR :Server too far away for authentication");
2513                         Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2514                         return false;
2515                 }
2516                 std::string description = params[3];
2517                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2518                 {
2519                         if ((x->Name == servername) && (x->RecvPass == password))
2520                         {
2521                                 TreeServer* CheckDupe = FindServer(sname);
2522                                 if (CheckDupe)
2523                                 {
2524                                         this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
2525                                         Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
2526                                         return false;
2527                                 }
2528                                 /* If the config says this link is encrypted, but the remote side
2529                                  * hasnt bothered to send the AES command before SERVER, then we
2530                                  * boot them off as we MUST have this connection encrypted.
2531                                  */
2532                                 if ((x->EncryptionKey != "") && (!this->ctx_in))
2533                                 {
2534                                         this->WriteLine("ERROR :This link requires AES encryption to be enabled. Plaintext connection refused.");
2535                                         Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, remote server did not enable AES.");
2536                                         return false;
2537                                 }
2538                                 Srv->SendOpers("*** Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
2539                                 this->InboundServerName = sname;
2540                                 this->InboundDescription = description;
2541                                 // this is good. Send our details: Our server name and description and hopcount of 0,
2542                                 // along with the sendpass from this block.
2543                                 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
2544                                 // move to the next state, we are now waiting for THEM.
2545                                 this->LinkState = WAIT_AUTH_2;
2546                                 return true;
2547                         }
2548                 }
2549                 this->WriteLine("ERROR :Invalid credentials");
2550                 Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, invalid link credentials");
2551                 return false;
2552         }
2553
2554         void Split(std::string line, std::deque<std::string> &n)
2555         {
2556                 n.clear();
2557                 irc::tokenstream tokens(line);
2558                 std::string param;
2559                 while ((param = tokens.GetToken()) != "")
2560                         n.push_back(param);
2561                 return;
2562         }
2563
2564         bool ProcessLine(std::string line)
2565         {
2566                 std::deque<std::string> params;
2567                 irc::string command;
2568                 std::string prefix;
2569                 
2570                 if (line.empty())
2571                         return true;
2572                 
2573                 line = line.substr(0, line.find_first_of("\r\n"));
2574                 
2575                 log(DEBUG,"IN: %s", line.c_str());
2576                 
2577                 this->Split(line.c_str(),params);
2578                         
2579                 if ((params[0][0] == ':') && (params.size() > 1))
2580                 {
2581                         prefix = params[0].substr(1);
2582                         params.pop_front();
2583                 }
2584
2585                 command = params[0].c_str();
2586                 params.pop_front();
2587
2588                 if ((!this->ctx_in) && (command == "AES"))
2589                 {
2590                         std::string sserv = params[0];
2591                         for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2592                         {
2593                                 if ((x->EncryptionKey != "") && (x->Name == sserv))
2594                                 {
2595                                         this->InitAES(x->EncryptionKey,sserv);
2596                                 }
2597                         }
2598
2599                         return true;
2600                 }
2601                 else if ((this->ctx_in) && (command == "AES"))
2602                 {
2603                         WriteOpers("*** \2AES\2: Encryption already enabled on this connection yet %s is trying to enable it twice!",params[0].c_str());
2604                 }
2605
2606                 switch (this->LinkState)
2607                 {
2608                         TreeServer* Node;
2609                         
2610                         case WAIT_AUTH_1:
2611                                 // Waiting for SERVER command from remote server. Server initiating
2612                                 // the connection sends the first SERVER command, listening server
2613                                 // replies with theirs if its happy, then if the initiator is happy,
2614                                 // it starts to send its net sync, which starts the merge, otherwise
2615                                 // it sends an ERROR.
2616                                 if (command == "PASS")
2617                                 {
2618                                         /* Silently ignored */
2619                                 }
2620                                 else if (command == "SERVER")
2621                                 {
2622                                         return this->Inbound_Server(params);
2623                                 }
2624                                 else if (command == "ERROR")
2625                                 {
2626                                         return this->Error(params);
2627                                 }
2628                                 else if (command == "USER")
2629                                 {
2630                                         this->WriteLine("ERROR :Client connections to this port are prohibited.");
2631                                         return false;
2632                                 }
2633                                 else if (command == "CAPAB")
2634                                 {
2635                                         return this->Capab(params);
2636                                 }
2637                                 else if ((command == "U") || (command == "S"))
2638                                 {
2639                                         this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
2640                                         return false;
2641                                 }
2642                                 else
2643                                 {
2644                                         this->WriteLine("ERROR :Invalid command in negotiation phase.");
2645                                         return false;
2646                                 }
2647                         break;
2648                         case WAIT_AUTH_2:
2649                                 // Waiting for start of other side's netmerge to say they liked our
2650                                 // password.
2651                                 if (command == "SERVER")
2652                                 {
2653                                         // cant do this, they sent it to us in the WAIT_AUTH_1 state!
2654                                         // silently ignore.
2655                                         return true;
2656                                 }
2657                                 else if ((command == "U") || (command == "S"))
2658                                 {
2659                                         this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
2660                                         return false;
2661                                 }
2662                                 else if (command == "BURST")
2663                                 {
2664                                         if (params.size())
2665                                         {
2666                                                 /* If a time stamp is provided, try and check syncronization */
2667                                                 time_t THEM = atoi(params[0].c_str());
2668                                                 long delta = THEM-time(NULL);
2669                                                 if ((delta < -600) || (delta > 600))
2670                                                 {
2671                                                         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));
2672                                                         this->WriteLine("ERROR :Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than ten minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
2673                                                         return false;
2674                                                 }
2675                                                 else if ((delta < -60) || (delta > 60))
2676                                                 {
2677                                                         WriteOpers("*** \2WARNING\2: Your clocks are out by %d seconds, please consider synching your clocks.",abs(delta));
2678                                                 }
2679                                         }
2680                                         this->LinkState = CONNECTED;
2681                                         Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
2682                                         TreeRoot->AddChild(Node);
2683                                         params.clear();
2684                                         params.push_back(InboundServerName);
2685                                         params.push_back("*");
2686                                         params.push_back("1");
2687                                         params.push_back(":"+InboundDescription);
2688                                         DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
2689                                         this->bursting = true;
2690                                         this->DoBurst(Node);
2691                                 }
2692                                 else if (command == "ERROR")
2693                                 {
2694                                         return this->Error(params);
2695                                 }
2696                                 else if (command == "CAPAB")
2697                                 {
2698                                         return this->Capab(params);
2699                                 }
2700                                 
2701                         break;
2702                         case LISTENER:
2703                                 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
2704                                 return false;
2705                         break;
2706                         case CONNECTING:
2707                                 if (command == "SERVER")
2708                                 {
2709                                         // another server we connected to, which was in WAIT_AUTH_1 state,
2710                                         // has just sent us their credentials. If we get this far, theyre
2711                                         // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
2712                                         // if we're happy with this, we should send our netburst which
2713                                         // kickstarts the merge.
2714                                         return this->Outbound_Reply_Server(params);
2715                                 }
2716                                 else if (command == "ERROR")
2717                                 {
2718                                         return this->Error(params);
2719                                 }
2720                         break;
2721                         case CONNECTED:
2722                                 // This is the 'authenticated' state, when all passwords
2723                                 // have been exchanged and anything past this point is taken
2724                                 // as gospel.
2725                                 
2726                                 if (prefix != "")
2727                                 {
2728                                         std::string direction = prefix;
2729                                         userrec* t = Srv->FindNick(prefix);
2730                                         if (t)
2731                                         {
2732                                                 direction = t->server;
2733                                         }
2734                                         TreeServer* route_back_again = BestRouteTo(direction);
2735                                         if ((!route_back_again) || (route_back_again->GetSocket() != this))
2736                                         {
2737                                                 if (route_back_again)
2738                                                         log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
2739                                                 return true;
2740                                         }
2741
2742                                         /* Fix by brain:
2743                                          * When there is activity on the socket, reset the ping counter so
2744                                          * that we're not wasting bandwidth pinging an active server.
2745                                          */ 
2746                                         route_back_again->SetNextPingTime(time(NULL) + 120);
2747                                         route_back_again->SetPingFlag();
2748                                 }
2749                                 
2750                                 if (command == "SVSMODE")
2751                                 {
2752                                         /* Services expects us to implement
2753                                          * SVSMODE. In inspircd its the same as
2754                                          * MODE anyway.
2755                                          */
2756                                         command = "MODE";
2757                                 }
2758                                 std::string target = "";
2759                                 /* Yes, know, this is a mess. Its reasonably fast though as we're
2760                                  * working with std::string here.
2761                                  */
2762                                 if ((command == "NICK") && (params.size() > 1))
2763                                 {
2764                                         return this->IntroduceClient(prefix,params);
2765                                 }
2766                                 else if (command == "FJOIN")
2767                                 {
2768                                         return this->ForceJoin(prefix,params);
2769                                 }
2770                                 else if (command == "STATS")
2771                                 {
2772                                         return this->Stats(prefix, params);
2773                                 }
2774                                 else if (command == "SERVER")
2775                                 {
2776                                         return this->RemoteServer(prefix,params);
2777                                 }
2778                                 else if (command == "ERROR")
2779                                 {
2780                                         return this->Error(params);
2781                                 }
2782                                 else if (command == "OPERTYPE")
2783                                 {
2784                                         return this->OperType(prefix,params);
2785                                 }
2786                                 else if (command == "FMODE")
2787                                 {
2788                                         return this->ForceMode(prefix,params);
2789                                 }
2790                                 else if (command == "KILL")
2791                                 {
2792                                         return this->RemoteKill(prefix,params);
2793                                 }
2794                                 else if (command == "FTOPIC")
2795                                 {
2796                                         return this->ForceTopic(prefix,params);
2797                                 }
2798                                 else if (command == "REHASH")
2799                                 {
2800                                         return this->RemoteRehash(prefix,params);
2801                                 }
2802                                 else if (command == "METADATA")
2803                                 {
2804                                         return this->MetaData(prefix,params);
2805                                 }
2806                                 else if (command == "PING")
2807                                 {
2808                                         /*
2809                                          * We just got a ping from a server that's bursting.
2810                                          * This can't be right, so set them to not bursting, and
2811                                          * apply their lines.
2812                                          */
2813                                         if (this->bursting)
2814                                         {
2815                                                 this->bursting = false;
2816                                                 apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2817                                         }
2818                                         if (prefix == "")
2819                                         {
2820                                                 prefix = this->GetName();
2821                                         }
2822                                         return this->LocalPing(prefix,params);
2823                                 }
2824                                 else if (command == "PONG")
2825                                 {
2826                                         /*
2827                                          * We just got a pong from a server that's bursting.
2828                                          * This can't be right, so set them to not bursting, and
2829                                          * apply their lines.
2830                                          */
2831                                         if (this->bursting)
2832                                         {
2833                                                 this->bursting = false;
2834                                                 apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2835                                         }
2836                                         if (prefix == "")
2837                                         {
2838                                                 prefix = this->GetName();
2839                                         }
2840                                         return this->LocalPong(prefix,params);
2841                                 }
2842                                 else if (command == "VERSION")
2843                                 {
2844                                         return this->ServerVersion(prefix,params);
2845                                 }
2846                                 else if (command == "FHOST")
2847                                 {
2848                                         return this->ChangeHost(prefix,params);
2849                                 }
2850                                 else if (command == "FNAME")
2851                                 {
2852                                         return this->ChangeName(prefix,params);
2853                                 }
2854                                 else if (command == "ADDLINE")
2855                                 {
2856                                         return this->AddLine(prefix,params);
2857                                 }
2858                                 else if (command == "SVSNICK")
2859                                 {
2860                                         if (prefix == "")
2861                                         {
2862                                                 prefix = this->GetName();
2863                                         }
2864                                         return this->ForceNick(prefix,params);
2865                                 }
2866                                 else if (command == "IDLE")
2867                                 {
2868                                         return this->Whois(prefix,params);
2869                                 }
2870                                 else if (command == "PUSH")
2871                                 {
2872                                         return this->Push(prefix,params);
2873                                 }
2874                                 else if (command == "TIME")
2875                                 {
2876                                         return this->Time(prefix,params);
2877                                 }
2878                                 else if ((command == "KICK") && (IsServer(prefix)))
2879                                 {
2880                                         std::string sourceserv = this->myhost;
2881                                         if (params.size() == 3)
2882                                         {
2883                                                 userrec* user = Srv->FindNick(params[1]);
2884                                                 chanrec* chan = Srv->FindChannel(params[0]);
2885                                                 if (user && chan)
2886                                                 {
2887                                                         server_kick_channel(user,chan,(char*)params[2].c_str(),false);
2888                                                 }
2889                                         }
2890                                         if (this->InboundServerName != "")
2891                                         {
2892                                                 sourceserv = this->InboundServerName;
2893                                         }
2894                                         return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
2895                                 }
2896                                 else if (command == "SVSJOIN")
2897                                 {
2898                                         if (prefix == "")
2899                                         {
2900                                                 prefix = this->GetName();
2901                                         }
2902                                         return this->ServiceJoin(prefix,params);
2903                                 }
2904                                 else if (command == "SQUIT")
2905                                 {
2906                                         if (params.size() == 2)
2907                                         {
2908                                                 this->Squit(FindServer(params[0]),params[1]);
2909                                         }
2910                                         return true;
2911                                 }
2912                                 else if (command == "ENDBURST")
2913                                 {
2914                                         this->bursting = false;
2915                                         apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2916                                         std::string sourceserv = this->myhost;
2917                                         if (this->InboundServerName != "")
2918                                         {
2919                                                 sourceserv = this->InboundServerName;
2920                                         }
2921                                         WriteOpers("*** Received end of netburst from \2%s\2",sourceserv.c_str());
2922                                         return true;
2923                                 }
2924                                 else
2925                                 {
2926                                         // not a special inter-server command.
2927                                         // Emulate the actual user doing the command,
2928                                         // this saves us having a huge ugly parser.
2929                                         userrec* who = Srv->FindNick(prefix);
2930                                         std::string sourceserv = this->myhost;
2931                                         if (this->InboundServerName != "")
2932                                         {
2933                                                 sourceserv = this->InboundServerName;
2934                                         }
2935                                         if (who)
2936                                         {
2937                                                 if ((command == "NICK") && (params.size() > 0))
2938                                                 {
2939                                                         /* On nick messages, check that the nick doesnt
2940                                                          * already exist here. If it does, kill their copy,
2941                                                          * and our copy.
2942                                                          */
2943                                                         userrec* x = Srv->FindNick(params[0]);
2944                                                         if ((x) && (x != who))
2945                                                         {
2946                                                                 std::deque<std::string> p;
2947                                                                 p.push_back(params[0]);
2948                                                                 p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
2949                                                                 DoOneToMany(Srv->GetServerName(),"KILL",p);
2950                                                                 p.clear();
2951                                                                 p.push_back(prefix);
2952                                                                 p.push_back("Nickname collision");
2953                                                                 DoOneToMany(Srv->GetServerName(),"KILL",p);
2954                                                                 Srv->QuitUser(x,"Nickname collision ("+prefix+" -> "+params[0]+")");
2955                                                                 userrec* y = Srv->FindNick(prefix);
2956                                                                 if (y)
2957                                                                 {
2958                                                                         Srv->QuitUser(y,"Nickname collision");
2959                                                                 }
2960                                                                 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
2961                                                         }
2962                                                 }
2963                                                 // its a user
2964                                                 target = who->server;
2965                                                 const char* strparams[127];
2966                                                 for (unsigned int q = 0; q < params.size(); q++)
2967                                                 {
2968                                                         strparams[q] = params[q].c_str();
2969                                                 }
2970                                                 if (!Srv->CallCommandHandler(command.c_str(), strparams, params.size(), who))
2971                                                 {
2972                                                         this->WriteLine("ERROR :Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
2973                                                         return false;
2974                                                 }
2975                                         }
2976                                         else
2977                                         {
2978                                                 // its not a user. Its either a server, or somethings screwed up.
2979                                                 if (IsServer(prefix))
2980                                                 {
2981                                                         target = Srv->GetServerName();
2982                                                 }
2983                                                 else
2984                                                 {
2985                                                         log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
2986                                                         return true;
2987                                                 }
2988                                         }
2989                                         return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
2990
2991                                 }
2992                                 return true;
2993                         break;
2994                 }
2995                 return true;
2996         }
2997
2998         virtual std::string GetName()
2999         {
3000                 std::string sourceserv = this->myhost;
3001                 if (this->InboundServerName != "")
3002                 {
3003                         sourceserv = this->InboundServerName;
3004                 }
3005                 return sourceserv;
3006         }
3007
3008         virtual void OnTimeout()
3009         {
3010                 if (this->LinkState == CONNECTING)
3011                 {
3012                         Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
3013                 }
3014         }
3015
3016         virtual void OnClose()
3017         {
3018                 // Connection closed.
3019                 // If the connection is fully up (state CONNECTED)
3020                 // then propogate a netsplit to all peers.
3021                 std::string quitserver = this->myhost;
3022                 if (this->InboundServerName != "")
3023                 {
3024                         quitserver = this->InboundServerName;
3025                 }
3026                 TreeServer* s = FindServer(quitserver);
3027                 if (s)
3028                 {
3029                         Squit(s,"Remote host closed the connection");
3030                 }
3031                 WriteOpers("Server '\2%s\2' closed the connection.",quitserver.c_str());
3032         }
3033
3034         virtual int OnIncomingConnection(int newsock, char* ip)
3035         {
3036                 /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
3037                  * or discovering if this port is the server port, we don't allow connections from any
3038                  * IPs for which we don't have a link block.
3039                  */
3040                 bool found = false;
3041                 vector<Link>::iterator i;
3042                 found = (std::find(ValidIPs.begin(), ValidIPs.end(), ip) != ValidIPs.end());
3043                 if (!found)
3044                 {
3045                         WriteOpers("Server connection from %s denied (no link blocks with that IP address)", ip);
3046                         close(newsock);
3047                         return false;
3048                 }
3049                 TreeSocket* s = new TreeSocket(newsock, ip);
3050                 Srv->AddSocket(s);
3051                 return true;
3052         }
3053 };
3054
3055 /** This class is used to resolve server hostnames during /connect and autoconnect.
3056  * As of 1.1, the resolver system is seperated out from InspSocket, so we must do this
3057  * resolver step first ourselves if we need it. This is totally nonblocking, and will
3058  * callback to OnLookupComplete or OnError when completed. Once it has completed we
3059  * will have an IP address which we can then use to continue our connection.
3060  */
3061 class ServernameResolver : public Resolver
3062 {       
3063  private:
3064         /** A copy of the Link tag info for what we're connecting to.
3065          * We take a copy, rather than using a pointer, just in case the
3066          * admin takes the tag away and rehashes while the domain is resolving.
3067          */
3068         Link MyLink;
3069  public:        
3070         ServernameResolver(const std::string &hostname, Link x) : Resolver(hostname, DNS_QUERY_FORWARD), MyLink(x)
3071         {
3072                 /* Nothing in here, folks */
3073         }
3074         
3075         void OnLookupComplete(const std::string &result)
3076         {
3077                 /* Initiate the connection, now that we have an IP to use.
3078                  * Passing a hostname directly to InspSocket causes it to
3079                  * just bail and set its FD to -1.
3080                  */
3081                 TreeServer* CheckDupe = FindServer(MyLink.Name.c_str());
3082                 if (!CheckDupe) /* Check that nobody tried to connect it successfully while we were resolving */
3083                 {
3084                         TreeSocket* newsocket = new TreeSocket(result,MyLink.Port,false,10,MyLink.Name.c_str());
3085                         if (newsocket->GetFd() > -1)
3086                         {
3087                                 /* We're all OK */
3088                                 Srv->AddSocket(newsocket);
3089                         }
3090                         else
3091                         {
3092                                 /* Something barfed, show the opers */
3093                                 WriteOpers("*** CONNECT: Error connecting \002%s\002: %s.",MyLink.Name.c_str(),strerror(errno));
3094                                 delete newsocket;
3095                         }
3096                 }
3097         }
3098
3099         void OnError(ResolverError e, const std::string &errormessage)
3100         {
3101                 /* Ooops! */
3102                 WriteOpers("*** CONNECT: Error connecting \002%s\002: Unable to resolve hostname - %s",MyLink.Name.c_str(),errormessage.c_str());
3103         }
3104 };
3105
3106 class SecurityIPResolver : public Resolver
3107 {
3108  private:
3109         Link MyLink;
3110  public:
3111         SecurityIPResolver(const std::string &hostname, Link x) : Resolver(hostname, DNS_QUERY_FORWARD), MyLink(x)
3112         {
3113         }
3114
3115         void OnLookupComplete(const std::string &result)
3116         {
3117                 log(DEBUG,"Security IP cache: Adding IP address '%s' for Link '%s'",result.c_str(),MyLink.Name.c_str());
3118                 ValidIPs.push_back(result);
3119         }
3120
3121         void OnError(ResolverError e, const std::string &errormessage)
3122         {
3123                 log(DEBUG,"Could not resolve IP associated with Link '%s': %s",MyLink.Name.c_str(),errormessage.c_str());
3124         }
3125 };
3126
3127 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
3128 {
3129         for (unsigned int c = 0; c < list.size(); c++)
3130         {
3131                 if (list[c] == server)
3132                 {
3133                         return;
3134                 }
3135         }
3136         list.push_back(server);
3137 }
3138
3139 // returns a list of DIRECT servernames for a specific channel
3140 void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
3141 {
3142         CUList *ulist = c->GetUsers();
3143         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
3144         {
3145                 if (i->second->fd < 0)
3146                 {
3147                         TreeServer* best = BestRouteTo(i->second->server);
3148                         if (best)
3149                                 AddThisServer(best,list);
3150                 }
3151         }
3152         return;
3153 }
3154
3155 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, irc::string command, std::deque<std::string> &params)
3156 {
3157         TreeServer* omitroute = BestRouteTo(omit);
3158         if ((command == "NOTICE") || (command == "PRIVMSG"))
3159         {
3160                 if (params.size() >= 2)
3161                 {
3162                         /* Prefixes */
3163                         if ((*(params[0].c_str()) == '@') || (*(params[0].c_str()) == '%') || (*(params[0].c_str()) == '+'))
3164                         {
3165                                 params[0] = params[0].substr(1, params[0].length()-1);
3166                         }
3167                         if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$'))
3168                         {
3169                                 // special routing for private messages/notices
3170                                 userrec* d = Srv->FindNick(params[0]);
3171                                 if (d)
3172                                 {
3173                                         std::deque<std::string> par;
3174                                         par.push_back(params[0]);
3175                                         par.push_back(":"+params[1]);
3176                                         DoOneToOne(prefix,command.c_str(),par,d->server);
3177                                         return true;
3178                                 }
3179                         }
3180                         else if (*(params[0].c_str()) == '$')
3181                         {
3182                                 std::deque<std::string> par;
3183                                 par.push_back(params[0]);
3184                                 par.push_back(":"+params[1]);
3185                                 DoOneToAllButSender(prefix,command.c_str(),par,omitroute->GetName());
3186                                 return true;
3187                         }
3188                         else
3189                         {
3190                                 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
3191                                 chanrec* c = Srv->FindChannel(params[0]);
3192                                 if (c)
3193                                 {
3194                                         std::deque<TreeServer*> list;
3195                                         GetListOfServersForChannel(c,list);
3196                                         log(DEBUG,"Got a list of %d servers",list.size());
3197                                         unsigned int lsize = list.size();
3198                                         for (unsigned int i = 0; i < lsize; i++)
3199                                         {
3200                                                 TreeSocket* Sock = list[i]->GetSocket();
3201                                                 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
3202                                                 {
3203                                                         log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
3204                                                         Sock->WriteLine(data);
3205                                                 }
3206                                         }
3207                                         return true;
3208                                 }
3209                         }
3210                 }
3211         }
3212         unsigned int items = TreeRoot->ChildCount();
3213         for (unsigned int x = 0; x < items; x++)
3214         {
3215                 TreeServer* Route = TreeRoot->GetChild(x);
3216                 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3217                 {
3218                         TreeSocket* Sock = Route->GetSocket();
3219                         Sock->WriteLine(data);
3220                 }
3221         }
3222         return true;
3223 }
3224
3225 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> &params, std::string omit)
3226 {
3227         TreeServer* omitroute = BestRouteTo(omit);
3228         std::string FullLine = ":" + prefix + " " + command;
3229         unsigned int words = params.size();
3230         for (unsigned int x = 0; x < words; x++)
3231         {
3232                 FullLine = FullLine + " " + params[x];
3233         }
3234         unsigned int items = TreeRoot->ChildCount();
3235         for (unsigned int x = 0; x < items; x++)
3236         {
3237                 TreeServer* Route = TreeRoot->GetChild(x);
3238                 // Send the line IF:
3239                 // The route has a socket (its a direct connection)
3240                 // The route isnt the one to be omitted
3241                 // The route isnt the path to the one to be omitted
3242                 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3243                 {
3244                         TreeSocket* Sock = Route->GetSocket();
3245                         Sock->WriteLine(FullLine);
3246                 }
3247         }
3248         return true;
3249 }
3250
3251 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> &params)
3252 {
3253         std::string FullLine = ":" + prefix + " " + command;
3254         unsigned int words = params.size();
3255         for (unsigned int x = 0; x < words; x++)
3256         {
3257                 FullLine = FullLine + " " + params[x];
3258         }
3259         unsigned int items = TreeRoot->ChildCount();
3260         for (unsigned int x = 0; x < items; x++)
3261         {
3262                 TreeServer* Route = TreeRoot->GetChild(x);
3263                 if (Route->GetSocket())
3264                 {
3265                         TreeSocket* Sock = Route->GetSocket();
3266                         Sock->WriteLine(FullLine);
3267                 }
3268         }
3269         return true;
3270 }
3271
3272 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> &params, std::string target)
3273 {
3274         TreeServer* Route = BestRouteTo(target);
3275         if (Route)
3276         {
3277                 std::string FullLine = ":" + prefix + " " + command;
3278                 unsigned int words = params.size();
3279                 for (unsigned int x = 0; x < words; x++)
3280                 {
3281                         FullLine = FullLine + " " + params[x];
3282                 }
3283                 if (Route->GetSocket())
3284                 {
3285                         TreeSocket* Sock = Route->GetSocket();
3286                         Sock->WriteLine(FullLine);
3287                 }
3288                 return true;
3289         }
3290         else
3291         {
3292                 return true;
3293         }
3294 }
3295
3296 std::vector<TreeSocket*> Bindings;
3297
3298 void ReadConfiguration(bool rebind)
3299 {
3300         Conf = new ConfigReader;
3301         if (rebind)
3302         {
3303                 for (int j =0; j < Conf->Enumerate("bind"); j++)
3304                 {
3305                         std::string Type = Conf->ReadValue("bind","type",j);
3306                         std::string IP = Conf->ReadValue("bind","address",j);
3307                         long Port = Conf->ReadInteger("bind","port",j,true);
3308                         if (Type == "servers")
3309                         {
3310                                 if (IP == "*")
3311                                 {
3312                                         IP = "";
3313                                 }
3314                                 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
3315                                 if (listener->GetState() == I_LISTENING)
3316                                 {
3317                                         Srv->AddSocket(listener);
3318                                         Bindings.push_back(listener);
3319                                 }
3320                                 else
3321                                 {
3322                                         log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
3323                                         listener->Close();
3324                                         DELETE(listener);
3325                                 }
3326                         }
3327                 }
3328         }
3329         FlatLinks = Conf->ReadFlag("options","flatlinks",0);
3330         HideULines = Conf->ReadFlag("options","hideulines",0);
3331         LinkBlocks.clear();
3332         ValidIPs.clear();
3333         for (int j =0; j < Conf->Enumerate("link"); j++)
3334         {
3335                 Link L;
3336                 L.Name = (Conf->ReadValue("link","name",j)).c_str();
3337                 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
3338                 L.Port = Conf->ReadInteger("link","port",j,true);
3339                 L.SendPass = Conf->ReadValue("link","sendpass",j);
3340                 L.RecvPass = Conf->ReadValue("link","recvpass",j);
3341                 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
3342                 L.EncryptionKey =  Conf->ReadValue("link","encryptionkey",j);
3343                 L.HiddenFromStats = Conf->ReadFlag("link","hidden",j);
3344                 L.NextConnectTime = time(NULL) + L.AutoConnect;
3345                 /* Bugfix by brain, do not allow people to enter bad configurations */
3346                 if ((L.IPAddr != "") && (L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
3347                 {
3348                         ValidIPs.push_back(L.IPAddr);
3349
3350                         /* Needs resolving */
3351                         insp_inaddr binip;
3352                         if (insp_aton(L.IPAddr.c_str(), &binip) < 1)
3353                         {
3354                                 try
3355                                 {
3356                                         SecurityIPResolver* sr = new SecurityIPResolver(L.IPAddr, L);
3357                                         Srv->AddResolver(sr);
3358                                 }
3359                                 catch (ModuleException& e)
3360                                 {
3361                                         log(DEBUG,"Error in resolver: %s",e.GetReason());
3362                                 }
3363                         }
3364
3365                         LinkBlocks.push_back(L);
3366                         log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
3367                 }
3368                 else
3369                 {
3370                         if (L.IPAddr == "")
3371                         {
3372                                 log(DEFAULT,"Invalid configuration for server '%s', IP address not defined!",L.Name.c_str());
3373                         }
3374                         else if (L.RecvPass == "")
3375                         {
3376                                 log(DEFAULT,"Invalid configuration for server '%s', recvpass not defined!",L.Name.c_str());
3377                         }
3378                         else if (L.SendPass == "")
3379                         {
3380                                 log(DEFAULT,"Invalid configuration for server '%s', sendpass not defined!",L.Name.c_str());
3381                         }
3382                         else if (L.Name == "")
3383                         {
3384                                 log(DEFAULT,"Invalid configuration, link tag without a name!");
3385                         }
3386                         else if (!L.Port)
3387                         {
3388                                 log(DEFAULT,"Invalid configuration for server '%s', no port specified!",L.Name.c_str());
3389                         }
3390                 }
3391         }
3392         DELETE(Conf);
3393 }
3394
3395
3396 class ModuleSpanningTree : public Module
3397 {
3398         std::vector<TreeSocket*> Bindings;
3399         int line;
3400         int NumServers;
3401         unsigned int max_local;
3402         unsigned int max_global;
3403         cmd_rconnect* command_rconnect;
3404
3405  public:
3406
3407         ModuleSpanningTree(Server* Me)
3408                 : Module::Module(Me), max_local(0), max_global(0)
3409         {
3410                 Srv = Me;
3411                 Bindings.clear();
3412
3413                 // Create the root of the tree
3414                 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
3415
3416                 ReadConfiguration(true);
3417
3418                 command_rconnect = new cmd_rconnect(this);
3419                 Srv->AddCommand(command_rconnect);
3420         }
3421
3422         void ShowLinks(TreeServer* Current, userrec* user, int hops)
3423         {
3424                 std::string Parent = TreeRoot->GetName();
3425                 if (Current->GetParent())
3426                 {
3427                         Parent = Current->GetParent()->GetName();
3428                 }
3429                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
3430                 {
3431                         if ((HideULines) && (Srv->IsUlined(Current->GetChild(q)->GetName())))
3432                         {
3433                                 if (*user->oper)
3434                                 {
3435                                          ShowLinks(Current->GetChild(q),user,hops+1);
3436                                 }
3437                         }
3438                         else
3439                         {
3440                                 ShowLinks(Current->GetChild(q),user,hops+1);
3441                         }
3442                 }
3443                 /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
3444                 if ((HideULines) && (Srv->IsUlined(Current->GetName())) && (!*user->oper))
3445                         return;
3446                 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());
3447         }
3448
3449         int CountLocalServs()
3450         {
3451                 return TreeRoot->ChildCount();
3452         }
3453
3454         int CountServs()
3455         {
3456                 return serverlist.size();
3457         }
3458
3459         void HandleLinks(const char** parameters, int pcnt, userrec* user)
3460         {
3461                 ShowLinks(TreeRoot,user,0);
3462                 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
3463                 return;
3464         }
3465
3466         void HandleLusers(const char** parameters, int pcnt, userrec* user)
3467         {
3468                 unsigned int n_users = usercnt();
3469
3470                 /* Only update these when someone wants to see them, more efficient */
3471                 if ((unsigned int)local_count() > max_local)
3472                         max_local = local_count();
3473                 if (n_users > max_global)
3474                         max_global = n_users;
3475
3476                 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());
3477                 if (usercount_opers())
3478                         WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
3479                 if (usercount_unknown())
3480                         WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
3481                 if (chancount())
3482                         WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
3483                 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
3484                 WriteServ(user->fd,"265 %s :Current Local Users: %d  Max: %d",user->nick,local_count(),max_local);
3485                 WriteServ(user->fd,"266 %s :Current Global Users: %d  Max: %d",user->nick,n_users,max_global);
3486                 return;
3487         }
3488
3489         // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
3490
3491         void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80], float &totusers, float &totservers)
3492         {
3493                 if (line < 128)
3494                 {
3495                         for (int t = 0; t < depth; t++)
3496                         {
3497                                 matrix[line][t] = ' ';
3498                         }
3499
3500                         // For Aligning, we need to work out exactly how deep this thing is, and produce
3501                         // a 'Spacer' String to compensate.
3502                         char spacer[40];
3503
3504                         memset(spacer,' ',40);
3505                         if ((40 - Current->GetName().length() - depth) > 1) {
3506                                 spacer[40 - Current->GetName().length() - depth] = '\0';
3507                         }
3508                         else
3509                         {
3510                                 spacer[5] = '\0';
3511                         }
3512
3513                         float percent;
3514                         char text[80];
3515                         if (clientlist.size() == 0) {
3516                                 // If there are no users, WHO THE HELL DID THE /MAP?!?!?!
3517                                 percent = 0;
3518                         }
3519                         else
3520                         {
3521                                 percent = ((float)Current->GetUserCount() / (float)clientlist.size()) * 100;
3522                         }
3523                         snprintf(text, 80, "%s %s%5d [%5.2f%%]", Current->GetName().c_str(), spacer, Current->GetUserCount(), percent);
3524                         totusers += Current->GetUserCount();
3525                         totservers++;
3526                         strlcpy(&matrix[line][depth],text,80);
3527                         line++;
3528                         for (unsigned int q = 0; q < Current->ChildCount(); q++)
3529                         {
3530                                 if ((HideULines) && (Srv->IsUlined(Current->GetChild(q)->GetName())))
3531                                 {
3532                                         if (*user->oper)
3533                                         {
3534                                                 ShowMap(Current->GetChild(q),user,(FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
3535                                         }
3536                                 }
3537                                 else
3538                                 {
3539                                         ShowMap(Current->GetChild(q),user,(FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
3540                                 }
3541                         }
3542                 }
3543         }
3544
3545         int HandleStats(const char** parameters, int pcnt, userrec* user)
3546         {
3547                 if (pcnt > 1)
3548                 {
3549                         /* Remote STATS, the server is within the 2nd parameter */
3550                         std::deque<std::string> params;
3551                         params.push_back(parameters[0]);
3552                         params.push_back(parameters[1]);
3553                         /* Send it out remotely, generate no reply yet */
3554                         TreeServer* s = FindServerMask(parameters[1]);
3555                         if (s)
3556                         {
3557                                 params[1] = s->GetName();
3558                                 DoOneToOne(user->nick, "STATS", params, s->GetName());
3559                         }
3560                         return 1;
3561                 }
3562                 return 0;
3563         }
3564
3565         // Ok, prepare to be confused.
3566         // After much mulling over how to approach this, it struck me that
3567         // the 'usual' way of doing a /MAP isnt the best way. Instead of
3568         // keeping track of a ton of ascii characters, and line by line
3569         // under recursion working out where to place them using multiplications
3570         // and divisons, we instead render the map onto a backplane of characters
3571         // (a character matrix), then draw the branches as a series of "L" shapes
3572         // from the nodes. This is not only friendlier on CPU it uses less stack.
3573
3574         void HandleMap(const char** parameters, int pcnt, userrec* user)
3575         {
3576                 // This array represents a virtual screen which we will
3577                 // "scratch" draw to, as the console device of an irc
3578                 // client does not provide for a proper terminal.
3579                 float totusers = 0;
3580                 float totservers = 0;
3581                 char matrix[128][80];
3582                 for (unsigned int t = 0; t < 128; t++)
3583                 {
3584                         matrix[t][0] = '\0';
3585                 }
3586                 line = 0;
3587                 // The only recursive bit is called here.
3588                 ShowMap(TreeRoot,user,0,matrix,totusers,totservers);
3589                 // Process each line one by one. The algorithm has a limit of
3590                 // 128 servers (which is far more than a spanning tree should have
3591                 // anyway, so we're ok). This limit can be raised simply by making
3592                 // the character matrix deeper, 128 rows taking 10k of memory.
3593                 for (int l = 1; l < line; l++)
3594                 {
3595                         // scan across the line looking for the start of the
3596                         // servername (the recursive part of the algorithm has placed
3597                         // the servers at indented positions depending on what they
3598                         // are related to)
3599                         int first_nonspace = 0;
3600                         while (matrix[l][first_nonspace] == ' ')
3601                         {
3602                                 first_nonspace++;
3603                         }
3604                         first_nonspace--;
3605                         // Draw the `- (corner) section: this may be overwritten by
3606                         // another L shape passing along the same vertical pane, becoming
3607                         // a |- (branch) section instead.
3608                         matrix[l][first_nonspace] = '-';
3609                         matrix[l][first_nonspace-1] = '`';
3610                         int l2 = l - 1;
3611                         // Draw upwards until we hit the parent server, causing possibly
3612                         // other corners (`-) to become branches (|-)
3613                         while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
3614                         {
3615                                 matrix[l2][first_nonspace-1] = '|';
3616                                 l2--;
3617                         }
3618                 }
3619                 // dump the whole lot to the user. This is the easy bit, honest.
3620                 for (int t = 0; t < line; t++)
3621                 {
3622                         WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
3623                 }
3624                 float avg_users = totusers / totservers;
3625                 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);
3626         WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
3627                 return;
3628         }
3629
3630         int HandleSquit(const char** parameters, int pcnt, userrec* user)
3631         {
3632                 TreeServer* s = FindServerMask(parameters[0]);
3633                 if (s)
3634                 {
3635                         if (s == TreeRoot)
3636                         {
3637                                  WriteServ(user->fd,"NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
3638                                 return 1;
3639                         }
3640                         TreeSocket* sock = s->GetSocket();
3641                         if (sock)
3642                         {
3643                                 log(DEBUG,"Splitting server %s",s->GetName().c_str());
3644                                 WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
3645                                 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
3646                                 Srv->RemoveSocket(sock);
3647                         }
3648                         else
3649                         {
3650                                 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
3651                         }
3652                 }
3653                 else
3654                 {
3655                          WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
3656                 }
3657                 return 1;
3658         }
3659
3660         int HandleTime(const char** parameters, int pcnt, userrec* user)
3661         {
3662                 if ((IS_LOCAL(user)) && (pcnt))
3663                 {
3664                         TreeServer* found = FindServerMask(parameters[0]);
3665                         if (found)
3666                         {
3667                                 // we dont' override for local server
3668                                 if (found == TreeRoot)
3669                                         return 0;
3670                                 
3671                                 std::deque<std::string> params;
3672                                 params.push_back(found->GetName());
3673                                 params.push_back(user->nick);
3674                                 DoOneToOne(Srv->GetServerName(),"TIME",params,found->GetName());
3675                         }
3676                         else
3677                         {
3678                                 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
3679                         }
3680                 }
3681                 return 1;
3682         }
3683
3684         int HandleRemoteWhois(const char** parameters, int pcnt, userrec* user)
3685         {
3686                 if ((IS_LOCAL(user)) && (pcnt > 1))
3687                 {
3688                         userrec* remote = Srv->FindNick(parameters[1]);
3689                         if ((remote) && (remote->fd < 0))
3690                         {
3691                                 std::deque<std::string> params;
3692                                 params.push_back(parameters[1]);
3693                                 DoOneToOne(user->nick,"IDLE",params,remote->server);
3694                                 return 1;
3695                         }
3696                         else if (!remote)
3697                         {
3698                                 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
3699                                 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
3700                                 return 1;
3701                         }
3702                 }
3703                 return 0;
3704         }
3705
3706         void DoPingChecks(time_t curtime)
3707         {
3708                 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
3709                 {
3710                         TreeServer* serv = TreeRoot->GetChild(j);
3711                         TreeSocket* sock = serv->GetSocket();
3712                         if (sock)
3713                         {
3714                                 if (curtime >= serv->NextPingTime())
3715                                 {
3716                                         if (serv->AnsweredLastPing())
3717                                         {
3718                                                 sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
3719                                                 serv->SetNextPingTime(curtime + 120);
3720                                         }
3721                                         else
3722                                         {
3723                                                 // they didnt answer, boot them
3724                                                 WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
3725                                                 sock->Squit(serv,"Ping timeout");
3726                                                 Srv->RemoveSocket(sock);
3727                                                 return;
3728                                         }
3729                                 }
3730                         }
3731                 }
3732         }
3733
3734         void AutoConnectServers(time_t curtime)
3735         {
3736                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
3737                 {
3738                         if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
3739                         {
3740                                 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
3741                                 x->NextConnectTime = curtime + x->AutoConnect;
3742                                 TreeServer* CheckDupe = FindServer(x->Name.c_str());
3743                                 if (!CheckDupe)
3744                                 {
3745                                         // an autoconnected server is not connected. Check if its time to connect it
3746                                         WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
3747
3748                                         insp_inaddr binip;
3749
3750                                         /* Do we already have an IP? If so, no need to resolve it. */
3751                                         if (insp_aton(x->IPAddr.c_str(), &binip) > 0)
3752                                         {
3753                                                 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name.c_str());
3754                                                 if (newsocket->GetFd() > -1)
3755                                                 {
3756                                                         Srv->AddSocket(newsocket);
3757                                                 }
3758                                                 else
3759                                                 {
3760                                                         WriteOpers("*** AUTOCONNECT: Error autoconnecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
3761                                                         delete newsocket;
3762                                                 }
3763                                         }
3764                                         else
3765                                         {
3766                                                 try
3767                                                 {
3768                                                         ServernameResolver* snr = new ServernameResolver(x->IPAddr, *x);
3769                                                         Srv->AddResolver(snr);
3770                                                 }
3771                                                 catch (ModuleException& e)
3772                                                 {
3773                                                         log(DEBUG,"Error in resolver: %s",e.GetReason());
3774                                                 }
3775                                         }
3776
3777                                 }
3778                         }
3779                 }
3780         }
3781
3782         int HandleVersion(const char** parameters, int pcnt, userrec* user)
3783         {
3784                 // we've already checked if pcnt > 0, so this is safe
3785                 TreeServer* found = FindServerMask(parameters[0]);
3786                 if (found)
3787                 {
3788                         std::string Version = found->GetVersion();
3789                         WriteServ(user->fd,"351 %s :%s",user->nick,Version.c_str());
3790                         if (found == TreeRoot)
3791                         {
3792                                 std::stringstream out(Config->data005);
3793                                 std::string token = "";
3794                                 std::string line5 = "";
3795                                 int token_counter = 0;
3796
3797                                 while (!out.eof())
3798                                 {
3799                                         out >> token;
3800                                         line5 = line5 + token + " ";   
3801                                         token_counter++;
3802
3803                                         if ((token_counter >= 13) || (out.eof() == true))
3804                                         {
3805                                                 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
3806                                                 line5 = "";
3807                                                 token_counter = 0;
3808                                         }
3809                                 }
3810                         }
3811                 }
3812                 else
3813                 {
3814                         WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
3815                 }
3816                 return 1;
3817         }
3818         
3819         int HandleConnect(const char** parameters, int pcnt, userrec* user)
3820         {
3821                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
3822                 {
3823                         if (Srv->MatchText(x->Name.c_str(),parameters[0]))
3824                         {
3825                                 TreeServer* CheckDupe = FindServer(x->Name.c_str());
3826                                 if (!CheckDupe)
3827                                 {
3828                                         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);
3829                                         insp_inaddr binip;
3830
3831                                         /* Do we already have an IP? If so, no need to resolve it. */
3832                                         if (insp_aton(x->IPAddr.c_str(), &binip) > 0)
3833                                         {
3834                                                 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name.c_str());
3835                                                 if (newsocket->GetFd() > -1)
3836                                                 {
3837                                                         Srv->AddSocket(newsocket);
3838                                                 }
3839                                                 else
3840                                                 {
3841                                                         WriteOpers("*** CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
3842                                                         delete newsocket;
3843                                                 }
3844                                         }
3845                                         else
3846                                         {
3847                                                 try
3848                                                 {
3849                                                         ServernameResolver* snr = new ServernameResolver(x->IPAddr, *x);
3850                                                         Srv->AddResolver(snr);
3851                                                 }
3852                                                 catch (ModuleException& e)
3853                                                 {
3854                                                         log(DEBUG,"Error in resolver: %s",e.GetReason());
3855                                                 }
3856                                         }
3857                                         return 1;
3858                                 }
3859                                 else
3860                                 {
3861                                         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());
3862                                         return 1;
3863                                 }
3864                         }
3865                 }
3866                 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
3867                 return 1;
3868         }
3869
3870         virtual int OnStats(char statschar, userrec* user, string_list &results)
3871         {
3872                 if (statschar == 'c')
3873                 {
3874                         for (unsigned int i = 0; i < LinkBlocks.size(); i++)
3875                         {
3876                                 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');
3877                                 results.push_back(Srv->GetServerName()+" 244 "+user->nick+" H * * "+LinkBlocks[i].Name.c_str());
3878                         }
3879                         results.push_back(Srv->GetServerName()+" 219 "+user->nick+" "+statschar+" :End of /STATS report");
3880                         WriteOpers("*** Notice: %s '%c' requested by %s (%s@%s)",(!strcmp(user->server,Config->ServerName) ? "Stats" : "Remote stats"),statschar,user->nick,user->ident,user->host);
3881                         return 1;
3882                 }
3883                 return 0;
3884         }
3885
3886         virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated)
3887         {
3888                 /* If the command doesnt appear to be valid, we dont want to mess with it. */
3889                 if (!validated)
3890                         return 0;
3891
3892                 if (command == "CONNECT")
3893                 {
3894                         return this->HandleConnect(parameters,pcnt,user);
3895                 }
3896                 else if (command == "STATS")
3897                 {
3898                         return this->HandleStats(parameters,pcnt,user);
3899                 }
3900                 else if (command == "SQUIT")
3901                 {
3902                         return this->HandleSquit(parameters,pcnt,user);
3903                 }
3904                 else if (command == "MAP")
3905                 {
3906                         this->HandleMap(parameters,pcnt,user);
3907                         return 1;
3908                 }
3909                 else if ((command == "TIME") && (pcnt > 0))
3910                 {
3911                         return this->HandleTime(parameters,pcnt,user);
3912                 }
3913                 else if (command == "LUSERS")
3914                 {
3915                         this->HandleLusers(parameters,pcnt,user);
3916                         return 1;
3917                 }
3918                 else if (command == "LINKS")
3919                 {
3920                         this->HandleLinks(parameters,pcnt,user);
3921                         return 1;
3922                 }
3923                 else if (command == "WHOIS")
3924                 {
3925                         if (pcnt > 1)
3926                         {
3927                                 // remote whois
3928                                 return this->HandleRemoteWhois(parameters,pcnt,user);
3929                         }
3930                 }
3931                 else if ((command == "VERSION") && (pcnt > 0))
3932                 {
3933                         this->HandleVersion(parameters,pcnt,user);
3934                         return 1;
3935                 }
3936                 else if (Srv->IsValidModuleCommand(command, pcnt, user))
3937                 {
3938                         // this bit of code cleverly routes all module commands
3939                         // to all remote severs *automatically* so that modules
3940                         // can just handle commands locally, without having
3941                         // to have any special provision in place for remote
3942                         // commands and linking protocols.
3943                         std::deque<std::string> params;
3944                         params.clear();
3945                         for (int j = 0; j < pcnt; j++)
3946                         {
3947                                 if (strchr(parameters[j],' '))
3948                                 {
3949                                         params.push_back(":" + std::string(parameters[j]));
3950                                 }
3951                                 else
3952                                 {
3953                                         params.push_back(std::string(parameters[j]));
3954                                 }
3955                         }
3956                         log(DEBUG,"Globally route '%s'",command.c_str());
3957                         DoOneToMany(user->nick,command,params);
3958                 }
3959                 return 0;
3960         }
3961
3962         virtual void OnGetServerDescription(const std::string &servername,std::string &description)
3963         {
3964                 TreeServer* s = FindServer(servername);
3965                 if (s)
3966                 {
3967                         description = s->GetDesc();
3968                 }
3969         }
3970
3971         virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
3972         {
3973                 if (IS_LOCAL(source))
3974                 {
3975                         std::deque<std::string> params;
3976                         params.push_back(dest->nick);
3977                         params.push_back(channel->name);
3978                         DoOneToMany(source->nick,"INVITE",params);
3979                 }
3980         }
3981
3982         virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, const std::string &topic)
3983         {
3984                 std::deque<std::string> params;
3985                 params.push_back(chan->name);
3986                 params.push_back(":"+topic);
3987                 DoOneToMany(user->nick,"TOPIC",params);
3988         }
3989
3990         virtual void OnWallops(userrec* user, const std::string &text)
3991         {
3992                 if (IS_LOCAL(user))
3993                 {
3994                         std::deque<std::string> params;
3995                         params.push_back(":"+text);
3996                         DoOneToMany(user->nick,"WALLOPS",params);
3997                 }
3998         }
3999
4000         virtual void OnUserNotice(userrec* user, void* dest, int target_type, const std::string &text, char status)
4001         {
4002                 if (target_type == TYPE_USER)
4003                 {
4004                         userrec* d = (userrec*)dest;
4005                         if ((d->fd < 0) && (IS_LOCAL(user)))
4006                         {
4007                                 std::deque<std::string> params;
4008                                 params.clear();
4009                                 params.push_back(d->nick);
4010                                 params.push_back(":"+text);
4011                                 DoOneToOne(user->nick,"NOTICE",params,d->server);
4012                         }
4013                 }
4014                 else if (target_type == TYPE_CHANNEL)
4015                 {
4016                         if (IS_LOCAL(user))
4017                         {
4018                                 chanrec *c = (chanrec*)dest;
4019                                 std::string cname = c->name;
4020                                 if (status)
4021                                         cname = status + cname;
4022                                 std::deque<TreeServer*> list;
4023                                 GetListOfServersForChannel(c,list);
4024                                 unsigned int ucount = list.size();
4025                                 for (unsigned int i = 0; i < ucount; i++)
4026                                 {
4027                                         TreeSocket* Sock = list[i]->GetSocket();
4028                                         if (Sock)
4029                                                 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+cname+" :"+text);
4030                                 }
4031                         }
4032                 }
4033                 else if (target_type == TYPE_SERVER)
4034                 {
4035                         if (IS_LOCAL(user))
4036                         {
4037                                 char* target = (char*)dest;
4038                                 std::deque<std::string> par;
4039                                 par.push_back(target);
4040                                 par.push_back(":"+text);
4041                                 DoOneToMany(user->nick,"NOTICE",par);
4042                         }
4043                 }
4044         }
4045
4046         virtual void OnUserMessage(userrec* user, void* dest, int target_type, const std::string &text, char status)
4047         {
4048                 if (target_type == TYPE_USER)
4049                 {
4050                         // route private messages which are targetted at clients only to the server
4051                         // which needs to receive them
4052                         userrec* d = (userrec*)dest;
4053                         if ((d->fd < 0) && (IS_LOCAL(user)))
4054                         {
4055                                 std::deque<std::string> params;
4056                                 params.clear();
4057                                 params.push_back(d->nick);
4058                                 params.push_back(":"+text);
4059                                 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
4060                         }
4061                 }
4062                 else if (target_type == TYPE_CHANNEL)
4063                 {
4064                         if (IS_LOCAL(user))
4065                         {
4066                                 chanrec *c = (chanrec*)dest;
4067                                 std::string cname = c->name;
4068                                 if (status)
4069                                         cname = status + cname;
4070                                 std::deque<TreeServer*> list;
4071                                 GetListOfServersForChannel(c,list);
4072                                 unsigned int ucount = list.size();
4073                                 for (unsigned int i = 0; i < ucount; i++)
4074                                 {
4075                                         TreeSocket* Sock = list[i]->GetSocket();
4076                                         if (Sock)
4077                                                 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+cname+" :"+text);
4078                                 }
4079                         }
4080                 }
4081                 else if (target_type == TYPE_SERVER)
4082                 {
4083                         if (IS_LOCAL(user))
4084                         {
4085                                 char* target = (char*)dest;
4086                                 std::deque<std::string> par;
4087                                 par.push_back(target);
4088                                 par.push_back(":"+text);
4089                                 DoOneToMany(user->nick,"PRIVMSG",par);
4090                         }
4091                 }
4092         }
4093
4094         virtual void OnBackgroundTimer(time_t curtime)
4095         {
4096                 AutoConnectServers(curtime);
4097                 DoPingChecks(curtime);
4098         }
4099
4100         virtual void OnUserJoin(userrec* user, chanrec* channel)
4101         {
4102                 // Only do this for local users
4103                 if (IS_LOCAL(user))
4104                 {
4105                         std::deque<std::string> params;
4106                         params.clear();
4107                         params.push_back(channel->name);
4108
4109                         if (channel->GetUserCounter() > 1)
4110                         {
4111                                 // not the first in the channel
4112                                 DoOneToMany(user->nick,"JOIN",params);
4113                         }
4114                         else
4115                         {
4116                                 // first in the channel, set up their permissions
4117                                 // and the channel TS with FJOIN.
4118                                 char ts[24];
4119                                 snprintf(ts,24,"%lu",(unsigned long)channel->age);
4120                                 params.clear();
4121                                 params.push_back(channel->name);
4122                                 params.push_back(ts);
4123                                 params.push_back("@"+std::string(user->nick));
4124                                 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
4125                         }
4126                 }
4127         }
4128
4129         virtual void OnChangeHost(userrec* user, const std::string &newhost)
4130         {
4131                 // only occurs for local clients
4132                 if (user->registered != REG_ALL)
4133                         return;
4134                 std::deque<std::string> params;
4135                 params.push_back(newhost);
4136                 DoOneToMany(user->nick,"FHOST",params);
4137         }
4138
4139         virtual void OnChangeName(userrec* user, const std::string &gecos)
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(gecos);
4146                 DoOneToMany(user->nick,"FNAME",params);
4147         }
4148
4149         virtual void OnUserPart(userrec* user, chanrec* channel, const std::string &partmessage)
4150         {
4151                 if (IS_LOCAL(user))
4152                 {
4153                         std::deque<std::string> params;
4154                         params.push_back(channel->name);
4155                         if (partmessage != "")
4156                                 params.push_back(":"+partmessage);
4157                         DoOneToMany(user->nick,"PART",params);
4158                 }
4159         }
4160
4161         virtual void OnUserConnect(userrec* user)
4162         {
4163                 char agestr[MAXBUF];
4164                 if (IS_LOCAL(user))
4165                 {
4166                         std::deque<std::string> params;
4167                         snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
4168                         params.push_back(agestr);
4169                         params.push_back(user->nick);
4170                         params.push_back(user->host);
4171                         params.push_back(user->dhost);
4172                         params.push_back(user->ident);
4173                         params.push_back("+"+std::string(user->FormatModes()));
4174                         params.push_back(user->GetIPString());
4175                         params.push_back(":"+std::string(user->fullname));
4176                         DoOneToMany(Srv->GetServerName(),"NICK",params);
4177
4178                         // User is Local, change needs to be reflected!
4179                         TreeServer* SourceServer = FindServer(user->server);
4180                         if (SourceServer)
4181                         {
4182                                 SourceServer->AddUserCount();
4183                         }
4184
4185                 }
4186         }
4187
4188         virtual void OnUserQuit(userrec* user, const std::string &reason)
4189         {
4190                 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
4191                 {
4192                         std::deque<std::string> params;
4193                         params.push_back(":"+reason);
4194                         DoOneToMany(user->nick,"QUIT",params);
4195                 }
4196                 // Regardless, We need to modify the user Counts..
4197                 TreeServer* SourceServer = FindServer(user->server);
4198                 if (SourceServer)
4199                 {
4200                         SourceServer->DelUserCount();
4201                 }
4202
4203         }
4204
4205         virtual void OnUserPostNick(userrec* user, const std::string &oldnick)
4206         {
4207                 if (IS_LOCAL(user))
4208                 {
4209                         std::deque<std::string> params;
4210                         params.push_back(user->nick);
4211                         DoOneToMany(oldnick,"NICK",params);
4212                 }
4213         }
4214
4215         virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, const std::string &reason)
4216         {
4217                 if ((source) && (IS_LOCAL(source)))
4218                 {
4219                         std::deque<std::string> params;
4220                         params.push_back(chan->name);
4221                         params.push_back(user->nick);
4222                         params.push_back(":"+reason);
4223                         DoOneToMany(source->nick,"KICK",params);
4224                 }
4225                 else if (!source)
4226                 {
4227                         std::deque<std::string> params;
4228                         params.push_back(chan->name);
4229                         params.push_back(user->nick);
4230                         params.push_back(":"+reason);
4231                         DoOneToMany(Srv->GetServerName(),"KICK",params);
4232                 }
4233         }
4234
4235         virtual void OnRemoteKill(userrec* source, userrec* dest, const std::string &reason)
4236         {
4237                 std::deque<std::string> params;
4238                 params.push_back(dest->nick);
4239                 params.push_back(":"+reason);
4240                 DoOneToMany(source->nick,"KILL",params);
4241         }
4242
4243         virtual void OnRehash(const std::string &parameter)
4244         {
4245                 if (parameter != "")
4246                 {
4247                         std::deque<std::string> params;
4248                         params.push_back(parameter);
4249                         DoOneToMany(Srv->GetServerName(),"REHASH",params);
4250                         // check for self
4251                         if (Srv->MatchText(Srv->GetServerName(),parameter))
4252                         {
4253                                 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
4254                                 Srv->RehashServer();
4255                         }
4256                 }
4257                 ReadConfiguration(false);
4258         }
4259
4260         // note: the protocol does not allow direct umode +o except
4261         // via NICK with 8 params. sending OPERTYPE infers +o modechange
4262         // locally.
4263         virtual void OnOper(userrec* user, const std::string &opertype)
4264         {
4265                 if (IS_LOCAL(user))
4266                 {
4267                         std::deque<std::string> params;
4268                         params.push_back(opertype);
4269                         DoOneToMany(user->nick,"OPERTYPE",params);
4270                 }
4271         }
4272
4273         void OnLine(userrec* source, const std::string &host, bool adding, char linetype, long duration, const std::string &reason)
4274         {
4275                 if (IS_LOCAL(source))
4276                 {
4277                         char type[8];
4278                         snprintf(type,8,"%cLINE",linetype);
4279                         std::string stype = type;
4280                         if (adding)
4281                         {
4282                                 char sduration[MAXBUF];
4283                                 snprintf(sduration,MAXBUF,"%ld",duration);
4284                                 std::deque<std::string> params;
4285                                 params.push_back(host);
4286                                 params.push_back(sduration);
4287                                 params.push_back(":"+reason);
4288                                 DoOneToMany(source->nick,stype,params);
4289                         }
4290                         else
4291                         {
4292                                 std::deque<std::string> params;
4293                                 params.push_back(host);
4294                                 DoOneToMany(source->nick,stype,params);
4295                         }
4296                 }
4297         }
4298
4299         virtual void OnAddGLine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
4300         {
4301                 OnLine(source,hostmask,true,'G',duration,reason);
4302         }
4303         
4304         virtual void OnAddZLine(long duration, userrec* source, const std::string &reason, const std::string &ipmask)
4305         {
4306                 OnLine(source,ipmask,true,'Z',duration,reason);
4307         }
4308
4309         virtual void OnAddQLine(long duration, userrec* source, const std::string &reason, const std::string &nickmask)
4310         {
4311                 OnLine(source,nickmask,true,'Q',duration,reason);
4312         }
4313
4314         virtual void OnAddELine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
4315         {
4316                 OnLine(source,hostmask,true,'E',duration,reason);
4317         }
4318
4319         virtual void OnDelGLine(userrec* source, const std::string &hostmask)
4320         {
4321                 OnLine(source,hostmask,false,'G',0,"");
4322         }
4323
4324         virtual void OnDelZLine(userrec* source, const std::string &ipmask)
4325         {
4326                 OnLine(source,ipmask,false,'Z',0,"");
4327         }
4328
4329         virtual void OnDelQLine(userrec* source, const std::string &nickmask)
4330         {
4331                 OnLine(source,nickmask,false,'Q',0,"");
4332         }
4333
4334         virtual void OnDelELine(userrec* source, const std::string &hostmask)
4335         {
4336                 OnLine(source,hostmask,false,'E',0,"");
4337         }
4338
4339         virtual void OnMode(userrec* user, void* dest, int target_type, const std::string &text)
4340         {
4341                 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
4342                 {
4343                         if (target_type == TYPE_USER)
4344                         {
4345                                 userrec* u = (userrec*)dest;
4346                                 std::deque<std::string> params;
4347                                 params.push_back(u->nick);
4348                                 params.push_back(text);
4349                                 DoOneToMany(user->nick,"MODE",params);
4350                         }
4351                         else
4352                         {
4353                                 chanrec* c = (chanrec*)dest;
4354                                 std::deque<std::string> params;
4355                                 params.push_back(c->name);
4356                                 params.push_back(text);
4357                                 DoOneToMany(user->nick,"MODE",params);
4358                         }
4359                 }
4360         }
4361
4362         virtual void OnSetAway(userrec* user)
4363         {
4364                 if (IS_LOCAL(user))
4365                 {
4366                         std::deque<std::string> params;
4367                         params.push_back(":"+std::string(user->awaymsg));
4368                         DoOneToMany(user->nick,"AWAY",params);
4369                 }
4370         }
4371
4372         virtual void OnCancelAway(userrec* user)
4373         {
4374                 if (IS_LOCAL(user))
4375                 {
4376                         std::deque<std::string> params;
4377                         params.clear();
4378                         DoOneToMany(user->nick,"AWAY",params);
4379                 }
4380         }
4381
4382         virtual void ProtoSendMode(void* opaque, int target_type, void* target, const std::string &modeline)
4383         {
4384                 TreeSocket* s = (TreeSocket*)opaque;
4385                 if (target)
4386                 {
4387                         if (target_type == TYPE_USER)
4388                         {
4389                                 userrec* u = (userrec*)target;
4390                                 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+ConvToStr(u->age)+" "+modeline);
4391                         }
4392                         else
4393                         {
4394                                 chanrec* c = (chanrec*)target;
4395                                 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" "+modeline);
4396                         }
4397                 }
4398         }
4399
4400         virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, const std::string &extname, const std::string &extdata)
4401         {
4402                 TreeSocket* s = (TreeSocket*)opaque;
4403                 if (target)
4404                 {
4405                         if (target_type == TYPE_USER)
4406                         {
4407                                 userrec* u = (userrec*)target;
4408                                 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+u->nick+" "+extname+" :"+extdata);
4409                         }
4410                         else if (target_type == TYPE_OTHER)
4411                         {
4412                                 s->WriteLine(":"+Srv->GetServerName()+" METADATA * "+extname+" :"+extdata);
4413                         }
4414                         else if (target_type == TYPE_CHANNEL)
4415                         {
4416                                 chanrec* c = (chanrec*)target;
4417                                 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+c->name+" "+extname+" :"+extdata);
4418                         }
4419                 }
4420         }
4421
4422         virtual void OnEvent(Event* event)
4423         {
4424                 if (event->GetEventID() == "send_metadata")
4425                 {
4426                         std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
4427                         if (params->size() < 3)
4428                                 return;
4429                         (*params)[2] = ":" + (*params)[2];
4430                         DoOneToMany(Srv->GetServerName(),"METADATA",*params);
4431                 }
4432                 else if (event->GetEventID() == "send_mode")
4433                 {
4434                         std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
4435                         if (params->size() < 2)
4436                                 return;
4437                         // Insert the TS value of the object, either userrec or chanrec
4438                         time_t ourTS = 0;
4439                         userrec* a = Srv->FindNick((*params)[0]);
4440                         if (a)
4441                         {
4442                                 ourTS = a->age;
4443                         }
4444                         else
4445                         {
4446                                 chanrec* a = Srv->FindChannel((*params)[0]);
4447                                 if (a)
4448                                 {
4449                                         ourTS = a->age;
4450                                 }
4451                         }
4452                         params->insert(params->begin() + 1,ConvToStr(ourTS));
4453                         DoOneToMany(Srv->GetServerName(),"FMODE",*params);
4454                 }
4455         }
4456
4457         virtual ~ModuleSpanningTree()
4458         {
4459         }
4460
4461         virtual Version GetVersion()
4462         {
4463                 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
4464         }
4465
4466         void Implements(char* List)
4467         {
4468                 List[I_OnPreCommand] = List[I_OnGetServerDescription] = List[I_OnUserInvite] = List[I_OnPostLocalTopicChange] = 1;
4469                 List[I_OnWallops] = List[I_OnUserNotice] = List[I_OnUserMessage] = List[I_OnBackgroundTimer] = 1;
4470                 List[I_OnUserJoin] = List[I_OnChangeHost] = List[I_OnChangeName] = List[I_OnUserPart] = List[I_OnUserConnect] = 1;
4471                 List[I_OnUserQuit] = List[I_OnUserPostNick] = List[I_OnUserKick] = List[I_OnRemoteKill] = List[I_OnRehash] = 1;
4472                 List[I_OnOper] = List[I_OnAddGLine] = List[I_OnAddZLine] = List[I_OnAddQLine] = List[I_OnAddELine] = 1;
4473                 List[I_OnDelGLine] = List[I_OnDelZLine] = List[I_OnDelQLine] = List[I_OnDelELine] = List[I_ProtoSendMode] = List[I_OnMode] = 1;
4474                 List[I_OnStats] = List[I_ProtoSendMetaData] = List[I_OnEvent] = List[I_OnSetAway] = List[I_OnCancelAway] = 1;
4475         }
4476
4477         /* It is IMPORTANT that m_spanningtree is the last module in the chain
4478          * so that any activity it sees is FINAL, e.g. we arent going to send out
4479          * a NICK message before m_cloaking has finished putting the +x on the user,
4480          * etc etc.
4481          * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
4482          * the module call queue.
4483          */
4484         Priority Prioritize()
4485         {
4486                 return PRIORITY_LAST;
4487         }
4488 };
4489
4490
4491 class ModuleSpanningTreeFactory : public ModuleFactory
4492 {
4493  public:
4494         ModuleSpanningTreeFactory()
4495         {
4496         }
4497         
4498         ~ModuleSpanningTreeFactory()
4499         {
4500         }
4501         
4502         virtual Module * CreateModule(Server* Me)
4503         {
4504                 TreeProtocolModule = new ModuleSpanningTree(Me);
4505                 return TreeProtocolModule;
4506         }
4507         
4508 };
4509
4510
4511 extern "C" void * init_module( void )
4512 {
4513         return new ModuleSpanningTreeFactory;
4514 }