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