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