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