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