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