]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree.cpp
Added <oper:swhois> to m_swhois, which will override <type:swhois> if specified
[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                 
1595                 /* Try and find the channel */
1596                 chanrec* chan = this->Instance->FindChan(channel);
1597
1598                 /* Initialize channel name in the mode parameters */
1599                 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
1600
1601                 /* default TS is a high value, which if we dont have this
1602                  * channel will let the other side apply their modes.
1603                  */
1604                 time_t ourTS = Instance->Time(true)+600;
1605
1606                 /* Does this channel exist? if it does, get its REAL timestamp */
1607                 if (chan)
1608                         ourTS = chan->age;
1609
1610                 /* In 1.1, if they have the newer channel, we immediately clear
1611                  * all status modes from our users. We then accept their modes.
1612                  * If WE have the newer channel its the other side's job to do this.
1613                  * Note that this causes the losing server to send out confirming
1614                  * FMODE lines.
1615                  */
1616                 if (ourTS > TS)
1617                 {
1618                         std::deque<std::string> param_list;
1619
1620                         if (chan)
1621                                 chan->age = TS;
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
1629                         param_list.push_back(channel);
1630                         /* Zap all the privilage modes on our side */
1631                         this->RemoveStatus(Instance->Config->ServerName, param_list);
1632                 }
1633
1634                 /* Put the final parameter of the FJOIN into a tokenstream ready to split it */
1635                 irc::tokenstream users(params[2]);
1636                 std::string item = "*";
1637
1638                 /* do this first, so our mode reversals are correctly received by other servers
1639                  * if there is a TS collision.
1640                  */
1641                 params[2] = ":" + params[2];
1642                 Utils->DoOneToAllButSender(source,"FJOIN",params,source);
1643
1644                 /* Now, process every 'prefixes,nick' pair */
1645                 while (item != "")
1646                 {
1647                         /* Find next user */
1648                         item = users.GetToken();
1649
1650                         const char* usr = item.c_str();
1651
1652                         /* Safety check just to make sure someones not sent us an FJOIN full of spaces
1653                          * (is this even possible?) */
1654                         if (usr && *usr)
1655                         {
1656                                 const char* permissions = usr;
1657                                 int ntimes = 0;
1658                                 char* nm = new char[MAXBUF];
1659                                 char* tnm = nm;
1660
1661                                 /* Iterate through all the prefix values, convert them from prefixes
1662                                  * to mode letters, and append them to the mode sequence
1663                                  */
1664                                 while ((*permissions) && (*permissions != ',') && (ntimes < MAXBUF))
1665                                 {
1666                                         ModeHandler* mh = Instance->Modes->FindPrefix(*permissions);
1667                                         if (mh)
1668                                         {
1669                                                 /* This is a valid prefix */
1670                                                 ntimes++;
1671                                                 *tnm++ = mh->GetModeChar();
1672                                         }
1673                                         else
1674                                         {
1675                                                 /* Not a valid prefix...
1676                                                  * danger bill bobbertson! (that's will robinsons older brother ;-) ...)
1677                                                  */
1678                                                 this->Instance->WriteOpers("ERROR: We received a user with an unknown prefix '%c'. Closed connection to avoid a desync.",*permissions);
1679                                                 this->WriteLine(std::string("ERROR :Invalid prefix '")+(*permissions)+"' in FJOIN");
1680                                                 return false;
1681                                         }
1682                                         usr++;
1683                                         permissions++;
1684                                 }
1685
1686                                 /* Null terminate modes */
1687                                 *tnm = 0;
1688                                 /* Advance past the comma, to the nick */
1689                                 usr++;
1690
1691                                 /* Check the user actually exists */
1692                                 who = this->Instance->FindNick(usr);
1693                                 if (who)
1694                                 {
1695                                         /* Did they get any modes? How many times? */
1696                                         strlcat(modestring, nm, MAXBUF);
1697                                         for (int k = 0; k < ntimes; k++)
1698                                                 mode_users[modectr++] = strdup(usr);
1699
1700                                         /* Free temporary buffer used for mode sequence */
1701                                         delete[] nm;
1702
1703                                         /* Check that the user's 'direction' is correct
1704                                          * based on the server sending the FJOIN. We must
1705                                          * check each nickname in turn, because the origin of
1706                                          * the FJOIN may be different to the origin of the nicks
1707                                          * in the command itself.
1708                                          */
1709                                         TreeServer* route_back_again = Utils->BestRouteTo(who->server);
1710                                         if ((!route_back_again) || (route_back_again->GetSocket() != this))
1711                                         {
1712                                                 /* Oh dear oh dear. */
1713                                                 Instance->Log(DEBUG,"Fake direction in FJOIN, user '%s'",who->nick);
1714                                                 continue;
1715                                         }
1716                                         /* Finally, we can actually place the user into the channel.
1717                                          * We're sure its right. Final answer, phone a friend.
1718                                          */
1719                                         chanrec::JoinUser(this->Instance, who, channel.c_str(), true, "");
1720
1721                                         /* Have we already queued up MAXMODES modes with parameters
1722                                          * (+qaohv) ready to be sent to the server?
1723                                          */
1724                                         if (modectr >= (MAXMODES-1))
1725                                         {
1726                                                 /* Only actually give the users any status if we lost
1727                                                  * the FJOIN or drew (equal timestamps).
1728                                                  * It isn't actually possible for ourTS to be > TS here,
1729                                                  * only possible to actually have ourTS == TS, or
1730                                                  * ourTS < TS, because if we lost, we already lowered
1731                                                  * our TS above before we entered this loop. We only
1732                                                  * check >= as a safety measure, in case someone stuffed
1733                                                  * up. If someone DID stuff up, it was most likely me.
1734                                                  * Note: I do not like baseball bats in the face...
1735                                                  */
1736                                                 if (ourTS >= TS)
1737                                                 {
1738                                                         Instance->Log(DEBUG,"Our our channel newer than theirs, accepting their modes");
1739                                                         this->Instance->SendMode((const char**)mode_users,modectr,who);
1740
1741                                                         /* Something stuffed up, and for some reason, the timestamp is
1742                                                          * NOT lowered right now and should be. Lower it. Usually this
1743                                                          * code won't be executed, doubtless someone will remove it some
1744                                                          * day soon.
1745                                                          */
1746                                                         if (ourTS > TS)
1747                                                         {
1748                                                                 Instance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",chan->name,ourTS,TS);
1749                                                                 chan->age = TS;
1750                                                                 ourTS = TS;
1751                                                         }
1752                                                 }
1753
1754                                                 /* Reset all this back to defaults, and
1755                                                  * free any ram we have left allocated.
1756                                                  */
1757                                                 strcpy(mode_users[1],"+");
1758                                                 for (unsigned int f = 2; f < modectr; f++)
1759                                                         free(mode_users[f]);
1760                                                 modectr = 2;
1761                                         }
1762                                 }
1763                                 else
1764                                 {
1765                                         /* Remember to free this */
1766                                         delete[] nm;
1767                                         /* If we got here, there's a nick in FJOIN which doesnt exist on this server.
1768                                          * We don't try to process the nickname here (that WOULD cause a segfault because
1769                                          * we'd be playing with null pointers) however, we DO pass the nickname on, just
1770                                          * in case somehow we're desynched, so that other users which might be able to see
1771                                          * the nickname get their fair chance to process it.
1772                                          */
1773                                         Instance->Log(SPARSE,"Warning! Invalid user in FJOIN to channel %s IGNORED", channel.c_str());
1774                                         continue;
1775                                 }
1776                         }
1777                 }
1778
1779                 /* there werent enough modes built up to flush it during FJOIN,
1780                  * or, there are a number left over. flush them out.
1781                  */
1782                 if ((modectr > 2) && (who) && (chan))
1783                 {
1784                         if (ourTS >= TS)
1785                         {
1786                                 /* Our channel is newer than theirs. Evil deeds must be afoot. */
1787                                 this->Instance->SendMode((const char**)mode_users,modectr,who);
1788                                 /* Yet again, we can't actually get a true value here, if everything else
1789                                  * is working as it should.
1790                                  */
1791                                 if (ourTS > TS)
1792                                 {
1793                                         Instance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",chan->name,ourTS,TS);
1794                                         chan->age = TS;
1795                                         ourTS = TS;
1796                                 }
1797                         }
1798
1799                         /* Free anything we have left to free */
1800                         for (unsigned int f = 2; f < modectr; f++)
1801                                 free(mode_users[f]);
1802                 }
1803
1804                 /* All done. That wasnt so bad was it, you can wipe
1805                  * the sweat from your forehead now. :-)
1806                  */
1807                 return true;
1808         }
1809
1810         /** NICK command */
1811         bool IntroduceClient(const std::string &source, std::deque<std::string> &params)
1812         {
1813                 if (params.size() < 8)
1814                         return true;
1815                 if (params.size() > 8)
1816                 {
1817                         this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[1]+"?)");
1818                         return true;
1819                 }
1820                 // NICK age nick host dhost ident +modes ip :gecos
1821                 //       0    1   2     3     4      5   6     7
1822                 time_t age = atoi(params[0].c_str());
1823                 
1824                 /* This used to have a pretty craq'y loop doing the same thing,
1825                  * now we just let the STL do the hard work (more efficiently)
1826                  */
1827                 std::string::size_type pos_after_plus = params[5].find_first_not_of('+');
1828                 if (pos_after_plus != std::string::npos)
1829                         params[5] = params[5].substr(pos_after_plus);
1830                 
1831                 const char* tempnick = params[1].c_str();
1832                 Instance->Log(DEBUG,"Introduce client %s!%s@%s",tempnick,params[4].c_str(),params[2].c_str());
1833                 
1834                 user_hash::iterator iter = this->Instance->clientlist.find(tempnick);
1835                 
1836                 if (iter != this->Instance->clientlist.end())
1837                 {
1838                         // nick collision
1839                         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);
1840                         this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+tempnick+" :Nickname collision");
1841                         userrec::QuitUser(this->Instance, iter->second, "Nickname collision");
1842                         return true;
1843                 }
1844
1845                 userrec* _new = new userrec(this->Instance);
1846                 this->Instance->clientlist[tempnick] = _new;
1847                 _new->SetFd(FD_MAGIC_NUMBER);
1848                 strlcpy(_new->nick, tempnick,NICKMAX-1);
1849                 strlcpy(_new->host, params[2].c_str(),63);
1850                 strlcpy(_new->dhost, params[3].c_str(),63);
1851                 _new->server = this->Instance->FindServerNamePtr(source.c_str());
1852                 strlcpy(_new->ident, params[4].c_str(),IDENTMAX);
1853                 strlcpy(_new->fullname, params[7].c_str(),MAXGECOS);
1854                 _new->registered = REG_ALL;
1855                 _new->signon = age;
1856                 
1857                 for (std::string::iterator v = params[5].begin(); v != params[5].end(); v++)
1858                         _new->modes[(*v)-65] = 1;
1859
1860 #ifdef SUPPORT_IP6LINKS
1861                 if (params[6].find_first_of(":") != std::string::npos)
1862                         _new->SetSockAddr(AF_INET6, params[6].c_str(), 0);
1863                 else
1864 #endif
1865                         _new->SetSockAddr(AF_INET, params[6].c_str(), 0);
1866
1867                 this->Instance->SNO->WriteToSnoMask('C',"Client connecting at %s: %s!%s@%s [%s]",_new->server,_new->nick,_new->ident,_new->host, _new->GetIPString());
1868
1869                 params[7] = ":" + params[7];
1870                 Utils->DoOneToAllButSender(source,"NICK",params,source);
1871
1872                 // Increment the Source Servers User Count..
1873                 TreeServer* SourceServer = Utils->FindServer(source);
1874                 if (SourceServer)
1875                 {
1876                         Instance->Log(DEBUG,"Found source server of %s",_new->nick);
1877                         SourceServer->AddUserCount();
1878                 }
1879
1880                 FOREACH_MOD_I(Instance,I_OnPostConnect,OnPostConnect(_new));
1881
1882                 return true;
1883         }
1884
1885         /** Send one or more FJOINs for a channel of users.
1886          * If the length of a single line is more than 480-NICKMAX
1887          * in length, it is split over multiple lines.
1888          */
1889         void SendFJoins(TreeServer* Current, chanrec* c)
1890         {
1891                 std::string buffer;
1892
1893                 Instance->Log(DEBUG,"Sending FJOINs to other server for %s",c->name);
1894                 char list[MAXBUF];
1895                 std::string individual_halfops = std::string(":")+this->Instance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age);
1896                 
1897                 size_t dlen, curlen;
1898                 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1899                 int numusers = 0;
1900                 char* ptr = list + dlen;
1901
1902                 CUList *ulist = c->GetUsers();
1903                 std::string modes = "";
1904                 std::string params = "";
1905
1906                 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1907                 {
1908                         // The first parameter gets a : before it
1909                         size_t ptrlen = snprintf(ptr, MAXBUF, " %s%s,%s", !numusers ? ":" : "", c->GetAllPrefixChars(i->second), i->second->nick);
1910
1911                         curlen += ptrlen;
1912                         ptr += ptrlen;
1913
1914                         numusers++;
1915
1916                         if (curlen > (480-NICKMAX))
1917                         {
1918                                 buffer.append(list).append("\r\n");
1919
1920                                 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1921                                 ptr = list + dlen;
1922                                 ptrlen = 0;
1923                                 numusers = 0;
1924                         }
1925                 }
1926
1927                 if (numusers)
1928                         buffer.append(list).append("\r\n");
1929
1930                 /* Sorry for the hax. Because newly created channels assume +nt,
1931                  * if this channel doesnt have +nt, explicitly send -n and -t for the missing modes.
1932                  */
1933                 bool inverted = false;
1934                 if (!c->IsModeSet('n'))
1935                 {
1936                         modes.append("-n");
1937                         inverted = true;
1938                 }
1939                 if (!c->IsModeSet('t'))
1940                 {
1941                         modes.append("-t");
1942                         inverted = true;
1943                 }
1944                 if (inverted)
1945                 {
1946                         modes.append("+");
1947                 }
1948
1949                 for (BanList::iterator b = c->bans.begin(); b != c->bans.end(); b++)
1950                 {
1951                         modes.append("b");
1952                         params.append(" ").append(b->data);
1953
1954                         if (params.length() >= MAXMODES)
1955                         {
1956                                 /* Wrap at MAXMODES */
1957                                 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");
1958                                 modes = "";
1959                                 params = "";
1960                         }
1961                 }
1962
1963                 buffer.append(":").append(this->Instance->Config->ServerName).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(c->ChanModes(true));
1964
1965                 /* Only send these if there are any */
1966                 if (!modes.empty())
1967                         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);
1968
1969                 this->WriteLine(buffer);
1970         }
1971
1972         /** Send G, Q, Z and E lines */
1973         void SendXLines(TreeServer* Current)
1974         {
1975                 char data[MAXBUF];
1976                 std::string buffer;
1977                 std::string n = this->Instance->Config->ServerName;
1978                 const char* sn = n.c_str();
1979                 int iterations = 0;
1980                 /* Yes, these arent too nice looking, but they get the job done */
1981                 for (std::vector<ZLine*>::iterator i = Instance->XLines->zlines.begin(); i != Instance->XLines->zlines.end(); i++, iterations++)
1982                 {
1983                         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);
1984                         buffer.append(data);
1985                 }
1986                 for (std::vector<QLine*>::iterator i = Instance->XLines->qlines.begin(); i != Instance->XLines->qlines.end(); i++, iterations++)
1987                 {
1988                         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);
1989                         buffer.append(data);
1990                 }
1991                 for (std::vector<GLine*>::iterator i = Instance->XLines->glines.begin(); i != Instance->XLines->glines.end(); i++, iterations++)
1992                 {
1993                         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);
1994                         buffer.append(data);
1995                 }
1996                 for (std::vector<ELine*>::iterator i = Instance->XLines->elines.begin(); i != Instance->XLines->elines.end(); i++, iterations++)
1997                 {
1998                         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);
1999                         buffer.append(data);
2000                 }
2001                 for (std::vector<ZLine*>::iterator i = Instance->XLines->pzlines.begin(); i != Instance->XLines->pzlines.end(); i++, iterations++)
2002                 {
2003                         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);
2004                         buffer.append(data);
2005                 }
2006                 for (std::vector<QLine*>::iterator i = Instance->XLines->pqlines.begin(); i != Instance->XLines->pqlines.end(); i++, iterations++)
2007                 {
2008                         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);
2009                         buffer.append(data);
2010                 }
2011                 for (std::vector<GLine*>::iterator i = Instance->XLines->pglines.begin(); i != Instance->XLines->pglines.end(); i++, iterations++)
2012                 {
2013                         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);
2014                         buffer.append(data);
2015                 }
2016                 for (std::vector<ELine*>::iterator i = Instance->XLines->pelines.begin(); i != Instance->XLines->pelines.end(); i++, iterations++)
2017                 {
2018                         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);
2019                         buffer.append(data);
2020                 }
2021
2022                 if (!buffer.empty())
2023                         this->WriteLine(buffer);
2024         }
2025
2026         /** Send channel modes and topics */
2027         void SendChannelModes(TreeServer* Current)
2028         {
2029                 char data[MAXBUF];
2030                 std::deque<std::string> list;
2031                 int iterations = 0;
2032                 std::string n = this->Instance->Config->ServerName;
2033                 const char* sn = n.c_str();
2034                 for (chan_hash::iterator c = this->Instance->chanlist.begin(); c != this->Instance->chanlist.end(); c++, iterations++)
2035                 {
2036                         SendFJoins(Current, c->second);
2037                         if (*c->second->topic)
2038                         {
2039                                 snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",sn,c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
2040                                 this->WriteLine(data);
2041                         }
2042                         FOREACH_MOD_I(this->Instance,I_OnSyncChannel,OnSyncChannel(c->second,(Module*)Utils->Creator,(void*)this));
2043                         list.clear();
2044                         c->second->GetExtList(list);
2045                         for (unsigned int j = 0; j < list.size(); j++)
2046                         {
2047                                 FOREACH_MOD_I(this->Instance,I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)Utils->Creator,(void*)this,list[j]));
2048                         }
2049                 }
2050         }
2051
2052         /** send all users and their oper state/modes */
2053         void SendUsers(TreeServer* Current)
2054         {
2055                 char data[MAXBUF];
2056                 std::deque<std::string> list;
2057                 std::string dataline;
2058                 int iterations = 0;
2059                 for (user_hash::iterator u = this->Instance->clientlist.begin(); u != this->Instance->clientlist.end(); u++, iterations++)
2060                 {
2061                         if (u->second->registered == REG_ALL)
2062                         {
2063                                 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);
2064                                 this->WriteLine(data);
2065                                 if (*u->second->oper)
2066                                 {
2067                                         snprintf(data,MAXBUF,":%s OPERTYPE %s", u->second->nick, u->second->oper);
2068                                         this->WriteLine(data);
2069                                 }
2070                                 if (*u->second->awaymsg)
2071                                 {
2072                                         snprintf(data,MAXBUF,":%s AWAY :%s", u->second->nick, u->second->awaymsg);
2073                                         this->WriteLine(data);
2074                                 }
2075                                 FOREACH_MOD_I(this->Instance,I_OnSyncUser,OnSyncUser(u->second,(Module*)Utils->Creator,(void*)this));
2076                                 list.clear();
2077                                 u->second->GetExtList(list);
2078                                 for (unsigned int j = 0; j < list.size(); j++)
2079                                 {
2080                                         FOREACH_MOD_I(this->Instance,I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)Utils->Creator,(void*)this,list[j]));
2081                                 }
2082                         }
2083                 }
2084         }
2085
2086         /** This function is called when we want to send a netburst to a local
2087          * server. There is a set order we must do this, because for example
2088          * users require their servers to exist, and channels require their
2089          * users to exist. You get the idea.
2090          */
2091         void DoBurst(TreeServer* s)
2092         {
2093                 std::string burst = "BURST "+ConvToStr(Instance->Time(true));
2094                 std::string endburst = "ENDBURST";
2095                 // Because by the end of the netburst, it  could be gone!
2096                 std::string name = s->GetName();
2097                 this->Instance->SNO->WriteToSnoMask('l',"Bursting to \2"+name+"\2.");
2098                 this->WriteLine(burst);
2099                 /* send our version string */
2100                 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" VERSION :"+this->Instance->GetVersionString());
2101                 /* Send server tree */
2102                 this->SendServers(Utils->TreeRoot,s,1);
2103                 /* Send users and their oper status */
2104                 this->SendUsers(s);
2105                 /* Send everything else (channel modes, xlines etc) */
2106                 this->SendChannelModes(s);
2107                 this->SendXLines(s);            
2108                 FOREACH_MOD_I(this->Instance,I_OnSyncOtherMetaData,OnSyncOtherMetaData((Module*)Utils->Creator,(void*)this));
2109                 this->WriteLine(endburst);
2110                 this->Instance->SNO->WriteToSnoMask('l',"Finished bursting to \2"+name+"\2.");
2111         }
2112
2113         /** This function is called when we receive data from a remote
2114          * server. We buffer the data in a std::string (it doesnt stay
2115          * there for long), reading using InspSocket::Read() which can
2116          * read up to 16 kilobytes in one operation.
2117          *
2118          * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
2119          * THE SOCKET OBJECT FOR US.
2120          */
2121         virtual bool OnDataReady()
2122         {
2123                 char* data = this->Read();
2124                 /* Check that the data read is a valid pointer and it has some content */
2125                 if (data && *data)
2126                 {
2127                         this->in_buffer.append(data);
2128                         /* While there is at least one new line in the buffer,
2129                          * do something useful (we hope!) with it.
2130                          */
2131                         while (in_buffer.find("\n") != std::string::npos)
2132                         {
2133                                 std::string ret = in_buffer.substr(0,in_buffer.find("\n")-1);
2134                                 in_buffer = in_buffer.substr(in_buffer.find("\n")+1,in_buffer.length()-in_buffer.find("\n"));
2135                                 /* Use rfind here not find, as theres more
2136                                  * chance of the \r being near the end of the
2137                                  * string, not the start.
2138                                  */
2139                                 if (ret.find("\r") != std::string::npos)
2140                                         ret = in_buffer.substr(0,in_buffer.find("\r")-1);
2141                                 /* Process this one, abort if it
2142                                  * didnt return true.
2143                                  */
2144                                 if (this->ctx_in)
2145                                 {
2146                                         char out[1024];
2147                                         char result[1024];
2148                                         memset(result,0,1024);
2149                                         memset(out,0,1024);
2150                                         /* ERROR + CAPAB is still allowed unencryped */
2151                                         if ((ret.substr(0,7) != "ERROR :") && (ret.substr(0,6) != "CAPAB "))
2152                                         {
2153                                                 int nbytes = from64tobits(out, ret.c_str(), 1024);
2154                                                 if ((nbytes > 0) && (nbytes < 1024))
2155                                                 {
2156                                                         ctx_in->Decrypt(out, result, nbytes, 0);
2157                                                         for (int t = 0; t < nbytes; t++)
2158                                                         {
2159                                                                 if (result[t] == '\7')
2160                                                                 {
2161                                                                         /* We only need to stick a \0 on the
2162                                                                          * first \7, the rest will be lost
2163                                                                          */
2164                                                                         result[t] = 0;
2165                                                                         break;
2166                                                                 }
2167                                                         }
2168                                                         ret = result;
2169                                                 }
2170                                         }
2171                                 }
2172                                 if (!this->ProcessLine(ret))
2173                                 {
2174                                         return false;
2175                                 }
2176                         }
2177                         return true;
2178                 }
2179                 /* EAGAIN returns an empty but non-NULL string, so this
2180                  * evaluates to TRUE for EAGAIN but to FALSE for EOF.
2181                  */
2182                 return (data && !*data);
2183         }
2184
2185         int WriteLine(std::string line)
2186         {
2187                 Instance->Log(DEBUG,"OUT: %s",line.c_str());
2188                 if (this->ctx_out)
2189                 {
2190                         char result[10240];
2191                         char result64[10240];
2192                         if (this->keylength)
2193                         {
2194                                 // pad it to the key length
2195                                 int n = this->keylength - (line.length() % this->keylength);
2196                                 if (n)
2197                                         line.append(n,'\7');
2198                         }
2199                         unsigned int ll = line.length();
2200                         ctx_out->Encrypt(line.c_str(), result, ll, 0);
2201                         to64frombits((unsigned char*)result64,(unsigned char*)result,ll);
2202                         line = result64;
2203                 }
2204                 line.append("\r\n");
2205                 return this->Write(line);
2206         }
2207
2208         /* Handle ERROR command */
2209         bool Error(std::deque<std::string> &params)
2210         {
2211                 if (params.size() < 1)
2212                         return false;
2213                 this->Instance->SNO->WriteToSnoMask('l',"ERROR from %s: %s",(InboundServerName != "" ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
2214                 /* we will return false to cause the socket to close. */
2215                 return false;
2216         }
2217
2218         /** remote MOTD. leet, huh? */
2219         bool Motd(const std::string &prefix, std::deque<std::string> &params)
2220         {
2221                 if (params.size() > 0)
2222                 {
2223                         if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
2224                         {
2225                                 /* It's for our server */
2226                                 string_list results;
2227                                 userrec* source = this->Instance->FindNick(prefix);
2228
2229                                 if (source)
2230                                 {
2231                                         std::deque<std::string> par;
2232                                         par.push_back(prefix);
2233                                         par.push_back("");
2234
2235                                         if (!Instance->Config->MOTD.size())
2236                                         {
2237                                                 par[1] = std::string("::")+Instance->Config->ServerName+" 422 "+source->nick+" :Message of the day file is missing.";
2238                                                 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2239                                                 return true;
2240                                         }
2241    
2242                                         par[1] = std::string("::")+Instance->Config->ServerName+" 375 "+source->nick+" :"+Instance->Config->ServerName+" message of the day";
2243                                         Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2244    
2245                                         for (unsigned int i = 0; i < Instance->Config->MOTD.size(); i++)
2246                                         {
2247                                                 par[1] = std::string("::")+Instance->Config->ServerName+" 372 "+source->nick+" :- "+Instance->Config->MOTD[i];
2248                                                 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2249                                         }
2250      
2251                                         par[1] = std::string("::")+Instance->Config->ServerName+" 376 "+source->nick+" End of message of the day.";
2252                                         Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2253                                 }
2254                         }
2255                         else
2256                         {
2257                                 /* Pass it on */
2258                                 userrec* source = this->Instance->FindNick(prefix);
2259                                 if (source)
2260                                         Utils->DoOneToOne(prefix, "MOTD", params, params[0]);
2261                         }
2262                 }
2263                 return true;
2264         }
2265
2266         /** remote ADMIN. leet, huh? */
2267         bool Admin(const std::string &prefix, std::deque<std::string> &params)
2268         {
2269                 if (params.size() > 0)
2270                 {
2271                         if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
2272                         {
2273                                 /* It's for our server */
2274                                 string_list results;
2275                                 userrec* source = this->Instance->FindNick(prefix);
2276
2277                                 if (source)
2278                                 {
2279                                         std::deque<std::string> par;
2280                                         par.push_back(prefix);
2281                                         par.push_back("");
2282
2283                                         par[1] = std::string("::")+Instance->Config->ServerName+" 256 "+source->nick+" :Administrative info for "+Instance->Config->ServerName;
2284                                         Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2285
2286                                         par[1] = std::string("::")+Instance->Config->ServerName+" 257 "+source->nick+" :Name     - "+Instance->Config->AdminName;
2287                                         Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2288
2289                                         par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :Nickname - "+Instance->Config->AdminNick;
2290                                         Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2291
2292                                         par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :E-Mail   - "+Instance->Config->AdminEmail;
2293                                         Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2294                                 }
2295                         }
2296                         else
2297                         {
2298                                 /* Pass it on */
2299                                 userrec* source = this->Instance->FindNick(prefix);
2300                                 if (source)
2301                                         Utils->DoOneToOne(prefix, "ADMIN", params, params[0]);
2302                         }
2303                 }
2304                 return true;
2305         }
2306
2307         bool Stats(const std::string &prefix, std::deque<std::string> &params)
2308         {
2309                 /* Get the reply to a STATS query if it matches this servername,
2310                  * and send it back as a load of PUSH queries
2311                  */
2312                 if (params.size() > 1)
2313                 {
2314                         if (this->Instance->MatchText(this->Instance->Config->ServerName, params[1]))
2315                         {
2316                                 /* It's for our server */
2317                                 string_list results;
2318                                 userrec* source = this->Instance->FindNick(prefix);
2319                                 if (source)
2320                                 {
2321                                         std::deque<std::string> par;
2322                                         par.push_back(prefix);
2323                                         par.push_back("");
2324                                         DoStats(this->Instance, *(params[0].c_str()), source, results);
2325                                         for (size_t i = 0; i < results.size(); i++)
2326                                         {
2327                                                 par[1] = "::" + results[i];
2328                                                 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2329                                         }
2330                                 }
2331                         }
2332                         else
2333                         {
2334                                 /* Pass it on */
2335                                 userrec* source = this->Instance->FindNick(prefix);
2336                                 if (source)
2337                                         Utils->DoOneToOne(prefix, "STATS", params, params[1]);
2338                         }
2339                 }
2340                 return true;
2341         }
2342
2343
2344         /** Because the core won't let users or even SERVERS set +o,
2345          * we use the OPERTYPE command to do this.
2346          */
2347         bool OperType(const std::string &prefix, std::deque<std::string> &params)
2348         {
2349                 if (params.size() != 1)
2350                 {
2351                         Instance->Log(DEBUG,"Received invalid oper type from %s",prefix.c_str());
2352                         return true;
2353                 }
2354                 std::string opertype = params[0];
2355                 userrec* u = this->Instance->FindNick(prefix);
2356                 if (u)
2357                 {
2358                         u->modes[UM_OPERATOR] = 1;
2359                         strlcpy(u->oper,opertype.c_str(),NICKMAX-1);
2360                         Utils->DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
2361                 }
2362                 return true;
2363         }
2364
2365         /** Because Andy insists that services-compatible servers must
2366          * implement SVSNICK and SVSJOIN, that's exactly what we do :p
2367          */
2368         bool ForceNick(const std::string &prefix, std::deque<std::string> &params)
2369         {
2370                 if (params.size() < 3)
2371                         return true;
2372
2373                 userrec* u = this->Instance->FindNick(params[0]);
2374
2375                 if (u)
2376                 {
2377                         Utils->DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
2378                         if (IS_LOCAL(u))
2379                         {
2380                                 std::deque<std::string> par;
2381                                 par.push_back(params[1]);
2382                                 /* This is not required as one is sent in OnUserPostNick below
2383                                  */
2384                                 //Utils->DoOneToMany(u->nick,"NICK",par);
2385                                 if (!u->ForceNickChange(params[1].c_str()))
2386                                 {
2387                                         userrec::QuitUser(this->Instance, u, "Nickname collision");
2388                                         return true;
2389                                 }
2390                                 u->age = atoi(params[2].c_str());
2391                         }
2392                 }
2393                 return true;
2394         }
2395
2396         bool ServiceJoin(const std::string &prefix, std::deque<std::string> &params)
2397         {
2398                 if (params.size() < 2)
2399                         return true;
2400
2401                 userrec* u = this->Instance->FindNick(params[0]);
2402
2403                 if (u)
2404                 {
2405                         chanrec::JoinUser(this->Instance, u, params[1].c_str(), false);
2406                         Utils->DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
2407                 }
2408                 return true;
2409         }
2410
2411         bool RemoteRehash(const std::string &prefix, std::deque<std::string> &params)
2412         {
2413                 if (params.size() < 1)
2414                         return false;
2415
2416                 std::string servermask = params[0];
2417
2418                 if (this->Instance->MatchText(this->Instance->Config->ServerName,servermask))
2419                 {
2420                         this->Instance->SNO->WriteToSnoMask('l',"Remote rehash initiated from server \002"+prefix+"\002.");
2421                         this->Instance->RehashServer();
2422                         Utils->ReadConfiguration(false);
2423                         InitializeDisabledCommands(Instance->Config->DisabledCommands, Instance);
2424                 }
2425                 Utils->DoOneToAllButSender(prefix,"REHASH",params,prefix);
2426                 return true;
2427         }
2428
2429         bool RemoteKill(const std::string &prefix, std::deque<std::string> &params)
2430         {
2431                 if (params.size() != 2)
2432                         return true;
2433
2434                 std::string nick = params[0];
2435                 userrec* u = this->Instance->FindNick(prefix);
2436                 userrec* who = this->Instance->FindNick(nick);
2437
2438                 if (who)
2439                 {
2440                         /* Prepend kill source, if we don't have one */
2441                         std::string sourceserv = prefix;
2442                         if (u)
2443                         {
2444                                 sourceserv = u->server;
2445                         }
2446                         if (*(params[1].c_str()) != '[')
2447                         {
2448                                 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
2449                         }
2450                         std::string reason = params[1];
2451                         params[1] = ":" + params[1];
2452                         Utils->DoOneToAllButSender(prefix,"KILL",params,sourceserv);
2453                         who->Write(":%s KILL %s :%s (%s)", sourceserv.c_str(), who->nick, sourceserv.c_str(), reason.c_str());
2454                         userrec::QuitUser(this->Instance,who,reason);
2455                 }
2456                 return true;
2457         }
2458
2459         bool LocalPong(const std::string &prefix, std::deque<std::string> &params)
2460         {
2461                 if (params.size() < 1)
2462                         return true;
2463
2464                 if (params.size() == 1)
2465                 {
2466                         TreeServer* ServerSource = Utils->FindServer(prefix);
2467                         if (ServerSource)
2468                         {
2469                                 ServerSource->SetPingFlag();
2470                         }
2471                 }
2472                 else
2473                 {
2474                         std::string forwardto = params[1];
2475                         if (forwardto == this->Instance->Config->ServerName)
2476                         {
2477                                 /*
2478                                  * this is a PONG for us
2479                                  * if the prefix is a user, check theyre local, and if they are,
2480                                  * dump the PONG reply back to their fd. If its a server, do nowt.
2481                                  * Services might want to send these s->s, but we dont need to yet.
2482                                  */
2483                                 userrec* u = this->Instance->FindNick(prefix);
2484
2485                                 if (u)
2486                                 {
2487                                         u->WriteServ("PONG %s %s",params[0].c_str(),params[1].c_str());
2488                                 }
2489                         }
2490                         else
2491                         {
2492                                 // not for us, pass it on :)
2493                                 Utils->DoOneToOne(prefix,"PONG",params,forwardto);
2494                         }
2495                 }
2496
2497                 return true;
2498         }
2499         
2500         bool MetaData(const std::string &prefix, std::deque<std::string> &params)
2501         {
2502                 if (params.size() < 3)
2503                         return true;
2504
2505                 TreeServer* ServerSource = Utils->FindServer(prefix);
2506
2507                 if (ServerSource)
2508                 {
2509                         if (params[0] == "*")
2510                         {
2511                                 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
2512                         }
2513                         else if (*(params[0].c_str()) == '#')
2514                         {
2515                                 chanrec* c = this->Instance->FindChan(params[0]);
2516                                 if (c)
2517                                 {
2518                                         FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
2519                                 }
2520                         }
2521                         else if (*(params[0].c_str()) != '#')
2522                         {
2523                                 userrec* u = this->Instance->FindNick(params[0]);
2524                                 if (u)
2525                                 {
2526                                         FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
2527                                 }
2528                         }
2529                 }
2530
2531                 params[2] = ":" + params[2];
2532                 Utils->DoOneToAllButSender(prefix,"METADATA",params,prefix);
2533                 return true;
2534         }
2535
2536         bool ServerVersion(const std::string &prefix, std::deque<std::string> &params)
2537         {
2538                 if (params.size() < 1)
2539                         return true;
2540
2541                 TreeServer* ServerSource = Utils->FindServer(prefix);
2542
2543                 if (ServerSource)
2544                 {
2545                         ServerSource->SetVersion(params[0]);
2546                 }
2547                 params[0] = ":" + params[0];
2548                 Utils->DoOneToAllButSender(prefix,"VERSION",params,prefix);
2549                 return true;
2550         }
2551
2552         bool ChangeHost(const std::string &prefix, std::deque<std::string> &params)
2553         {
2554                 if (params.size() < 1)
2555                         return true;
2556
2557                 userrec* u = this->Instance->FindNick(prefix);
2558
2559                 if (u)
2560                 {
2561                         u->ChangeDisplayedHost(params[0].c_str());
2562                         Utils->DoOneToAllButSender(prefix,"FHOST",params,u->server);
2563                 }
2564                 return true;
2565         }
2566
2567         bool AddLine(const std::string &prefix, std::deque<std::string> &params)
2568         {
2569                 if (params.size() < 6)
2570                         return true;
2571
2572                 bool propogate = false;
2573
2574                 switch (*(params[0].c_str()))
2575                 {
2576                         case 'Z':
2577                                 propogate = Instance->XLines->add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2578                                 Instance->XLines->zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2579                         break;
2580                         case 'Q':
2581                                 propogate = Instance->XLines->add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2582                                 Instance->XLines->qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2583                         break;
2584                         case 'E':
2585                                 propogate = Instance->XLines->add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2586                                 Instance->XLines->eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2587                         break;
2588                         case 'G':
2589                                 propogate = Instance->XLines->add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2590                                 Instance->XLines->gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2591                         break;
2592                         case 'K':
2593                                 propogate = Instance->XLines->add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2594                         break;
2595                         default:
2596                                 /* Just in case... */
2597                                 this->Instance->SNO->WriteToSnoMask('x',"\2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");
2598                                 propogate = false;
2599                         break;
2600                 }
2601
2602                 /* Send it on its way */
2603                 if (propogate)
2604                 {
2605                         if (atoi(params[4].c_str()))
2606                         {
2607                                 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());
2608                         }
2609                         else
2610                         {
2611                                 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());
2612                         }
2613                         params[5] = ":" + params[5];
2614                         Utils->DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
2615                 }
2616                 if (!this->bursting)
2617                 {
2618                         Instance->Log(DEBUG,"Applying lines...");
2619                         Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2620                 }
2621                 return true;
2622         }
2623
2624         bool ChangeName(const std::string &prefix, std::deque<std::string> &params)
2625         {
2626                 if (params.size() < 1)
2627                         return true;
2628
2629                 userrec* u = this->Instance->FindNick(prefix);
2630
2631                 if (u)
2632                 {
2633                         u->ChangeName(params[0].c_str());
2634                         params[0] = ":" + params[0];
2635                         Utils->DoOneToAllButSender(prefix,"FNAME",params,u->server);
2636                 }
2637                 return true;
2638         }
2639
2640         bool Whois(const std::string &prefix, std::deque<std::string> &params)
2641         {
2642                 if (params.size() < 1)
2643                         return true;
2644
2645                 Instance->Log(DEBUG,"In IDLE command");
2646                 userrec* u = this->Instance->FindNick(prefix);
2647
2648                 if (u)
2649                 {
2650                         Instance->Log(DEBUG,"USER EXISTS: %s",u->nick);
2651                         // an incoming request
2652                         if (params.size() == 1)
2653                         {
2654                                 userrec* x = this->Instance->FindNick(params[0]);
2655                                 if ((x) && (IS_LOCAL(x)))
2656                                 {
2657                                         userrec* x = this->Instance->FindNick(params[0]);
2658                                         char signon[MAXBUF];
2659                                         char idle[MAXBUF];
2660
2661                                         snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
2662                                         snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-Instance->Time(true)));
2663                                         std::deque<std::string> par;
2664                                         par.push_back(prefix);
2665                                         par.push_back(signon);
2666                                         par.push_back(idle);
2667                                         // ours, we're done, pass it BACK
2668                                         Utils->DoOneToOne(params[0],"IDLE",par,u->server);
2669                                 }
2670                                 else
2671                                 {
2672                                         // not ours pass it on
2673                                         Utils->DoOneToOne(prefix,"IDLE",params,x->server);
2674                                 }
2675                         }
2676                         else if (params.size() == 3)
2677                         {
2678                                 std::string who_did_the_whois = params[0];
2679                                 userrec* who_to_send_to = this->Instance->FindNick(who_did_the_whois);
2680                                 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2681                                 {
2682                                         // an incoming reply to a whois we sent out
2683                                         std::string nick_whoised = prefix;
2684                                         unsigned long signon = atoi(params[1].c_str());
2685                                         unsigned long idle = atoi(params[2].c_str());
2686                                         if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2687                                                 do_whois(this->Instance,who_to_send_to,u,signon,idle,nick_whoised.c_str());
2688                                 }
2689                                 else
2690                                 {
2691                                         // not ours, pass it on
2692                                         Utils->DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
2693                                 }
2694                         }
2695                 }
2696                 return true;
2697         }
2698
2699         bool Push(const std::string &prefix, std::deque<std::string> &params)
2700         {
2701                 if (params.size() < 2)
2702                         return true;
2703
2704                 userrec* u = this->Instance->FindNick(params[0]);
2705
2706                 if (!u)
2707                         return true;
2708
2709                 if (IS_LOCAL(u))
2710                 {
2711                         u->Write(params[1]);
2712                 }
2713                 else
2714                 {
2715                         // continue the raw onwards
2716                         params[1] = ":" + params[1];
2717                         Utils->DoOneToOne(prefix,"PUSH",params,u->server);
2718                 }
2719                 return true;
2720         }
2721
2722         bool HandleSetTime(const std::string &prefix, std::deque<std::string> &params)
2723         {
2724                 if (!params.size() || !Utils->EnableTimeSync)
2725                         return true;
2726                 
2727                 bool force = false;
2728                 
2729                 if ((params.size() == 2) && (params[1] == "FORCE"))
2730                         force = true;
2731                 
2732                 time_t rts = atoi(params[0].c_str());
2733                 time_t us = Instance->Time(true);
2734                 
2735                 if (rts == us)
2736                 {
2737                         Instance->Log(DEBUG, "Timestamp from %s is equal", prefix.c_str());
2738                         
2739                         Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
2740                 }
2741                 else if (force || (rts < us))
2742                 {
2743                         int old = Instance->SetTimeDelta(rts - us);
2744                         Instance->Log(DEBUG, "%s TS (diff %d) from %s applied (old delta was %d)", (force) ? "Forced" : "Lower", rts - us, prefix.c_str(), old);
2745                         
2746                         Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
2747                 }
2748                 else
2749                 {
2750                         Instance->Log(DEBUG, "Higher TS (diff %d) from %s overridden", us - rts, prefix.c_str());
2751                         
2752                         std::deque<std::string> oparams;
2753                         oparams.push_back(ConvToStr(us));
2754                         
2755                         Utils->DoOneToMany(prefix, "TIMESET", oparams);
2756                 }
2757                 
2758                 return true;
2759         }
2760
2761         bool Time(const std::string &prefix, std::deque<std::string> &params)
2762         {
2763                 // :source.server TIME remote.server sendernick
2764                 // :remote.server TIME source.server sendernick TS
2765                 if (params.size() == 2)
2766                 {
2767                         // someone querying our time?
2768                         if (this->Instance->Config->ServerName == params[0])
2769                         {
2770                                 userrec* u = this->Instance->FindNick(params[1]);
2771                                 if (u)
2772                                 {
2773                                         params.push_back(ConvToStr(Instance->Time(false)));
2774                                         params[0] = prefix;
2775                                         Utils->DoOneToOne(this->Instance->Config->ServerName,"TIME",params,params[0]);
2776                                 }
2777                         }
2778                         else
2779                         {
2780                                 // not us, pass it on
2781                                 userrec* u = this->Instance->FindNick(params[1]);
2782                                 if (u)
2783                                         Utils->DoOneToOne(prefix,"TIME",params,params[0]);
2784                         }
2785                 }
2786                 else if (params.size() == 3)
2787                 {
2788                         // a response to a previous TIME
2789                         userrec* u = this->Instance->FindNick(params[1]);
2790                         if ((u) && (IS_LOCAL(u)))
2791                         {
2792                         time_t rawtime = atol(params[2].c_str());
2793                         struct tm * timeinfo;
2794                         timeinfo = localtime(&rawtime);
2795                                 char tms[26];
2796                                 snprintf(tms,26,"%s",asctime(timeinfo));
2797                                 tms[24] = 0;
2798                         u->WriteServ("391 %s %s :%s",u->nick,prefix.c_str(),tms);
2799                         }
2800                         else
2801                         {
2802                                 if (u)
2803                                         Utils->DoOneToOne(prefix,"TIME",params,u->server);
2804                         }
2805                 }
2806                 return true;
2807         }
2808         
2809         bool LocalPing(const std::string &prefix, std::deque<std::string> &params)
2810         {
2811                 if (params.size() < 1)
2812                         return true;
2813
2814                 if (params.size() == 1)
2815                 {
2816                         std::string stufftobounce = params[0];
2817                         this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" PONG "+stufftobounce);
2818                         return true;
2819                 }
2820                 else
2821                 {
2822                         std::string forwardto = params[1];
2823                         if (forwardto == this->Instance->Config->ServerName)
2824                         {
2825                                 // this is a ping for us, send back PONG to the requesting server
2826                                 params[1] = params[0];
2827                                 params[0] = forwardto;
2828                                 Utils->DoOneToOne(forwardto,"PONG",params,params[1]);
2829                         }
2830                         else
2831                         {
2832                                 // not for us, pass it on :)
2833                                 Utils->DoOneToOne(prefix,"PING",params,forwardto);
2834                         }
2835                         return true;
2836                 }
2837         }
2838
2839         bool RemoveStatus(const std::string &prefix, std::deque<std::string> &params)
2840         {
2841                 if (params.size() < 1)
2842                         return true;
2843
2844                 chanrec* c = Instance->FindChan(params[0]);
2845
2846                 if (c)
2847                 {
2848                         irc::modestacker modestack(false);
2849                         CUList *ulist = c->GetUsers();
2850                         const char* y[127];
2851                         std::deque<std::string> stackresult;
2852                         std::string x;
2853
2854                         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
2855                         {
2856                                 std::string modesequence = Instance->Modes->ModeString(i->second, c);
2857                                 if (modesequence.length())
2858                                 {
2859                                         Instance->Log(DEBUG,"Mode sequence = '%s'",modesequence.c_str());
2860                                         irc::spacesepstream sep(modesequence);
2861                                         std::string modeletters = sep.GetToken();
2862                                         Instance->Log(DEBUG,"Mode letters = '%s'",modeletters.c_str());
2863                                         
2864                                         while (!modeletters.empty())
2865                                         {
2866                                                 char mletter = *(modeletters.begin());
2867                                                 modestack.Push(mletter,sep.GetToken());
2868                                                 Instance->Log(DEBUG,"Push letter = '%c'",mletter);
2869                                                 modeletters.erase(modeletters.begin());
2870                                                 Instance->Log(DEBUG,"Mode letters = '%s'",modeletters.c_str());
2871                                         }
2872                                 }
2873                         }
2874
2875                         while (modestack.GetStackedLine(stackresult))
2876                         {
2877                                 Instance->Log(DEBUG,"Stacked line size %d",stackresult.size());
2878                                 stackresult.push_front(ConvToStr(c->age));
2879                                 stackresult.push_front(c->name);
2880                                 Utils->DoOneToMany(Instance->Config->ServerName, "FMODE", stackresult);
2881                                 stackresult.erase(stackresult.begin() + 1);
2882                                 Instance->Log(DEBUG,"Stacked items:");
2883                                 for (size_t z = 0; z < stackresult.size(); z++)
2884                                 {
2885                                         y[z] = stackresult[z].c_str();
2886                                         Instance->Log(DEBUG,"\tstackresult[%d]='%s'",z,stackresult[z].c_str());
2887                                 }
2888                                 userrec* n = new userrec(Instance);
2889                                 n->SetFd(FD_MAGIC_NUMBER);
2890                                 Instance->SendMode(y, stackresult.size(), n);
2891                                 delete n;
2892                         }
2893                 }
2894                 return true;
2895         }
2896
2897         bool RemoteServer(const std::string &prefix, std::deque<std::string> &params)
2898         {
2899                 if (params.size() < 4)
2900                         return false;
2901
2902                 std::string servername = params[0];
2903                 std::string password = params[1];
2904                 // hopcount is not used for a remote server, we calculate this ourselves
2905                 std::string description = params[3];
2906                 TreeServer* ParentOfThis = Utils->FindServer(prefix);
2907
2908                 if (!ParentOfThis)
2909                 {
2910                         this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
2911                         return false;
2912                 }
2913                 TreeServer* CheckDupe = Utils->FindServer(servername);
2914                 if (CheckDupe)
2915                 {
2916                         this->WriteLine("ERROR :Server "+servername+" already exists!");
2917                         this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+servername+"\2 denied, already exists");
2918                         return false;
2919                 }
2920                 TreeServer* Node = new TreeServer(this->Utils,this->Instance,servername,description,ParentOfThis,NULL);
2921                 ParentOfThis->AddChild(Node);
2922                 params[3] = ":" + params[3];
2923                 Utils->DoOneToAllButSender(prefix,"SERVER",params,prefix);
2924                 this->Instance->SNO->WriteToSnoMask('l',"Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
2925                 return true;
2926         }
2927
2928         bool Outbound_Reply_Server(std::deque<std::string> &params)
2929         {
2930                 if (params.size() < 4)
2931                         return false;
2932
2933                 irc::string servername = params[0].c_str();
2934                 std::string sname = params[0];
2935                 std::string password = params[1];
2936                 int hops = atoi(params[2].c_str());
2937
2938                 if (hops)
2939                 {
2940                         this->WriteLine("ERROR :Server too far away for authentication");
2941                         this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2942                         return false;
2943                 }
2944                 std::string description = params[3];
2945                 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
2946                 {
2947                         if ((x->Name == servername) && (x->RecvPass == password))
2948                         {
2949                                 TreeServer* CheckDupe = Utils->FindServer(sname);
2950                                 if (CheckDupe)
2951                                 {
2952                                         this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
2953                                         this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
2954                                         return false;
2955                                 }
2956                                 // Begin the sync here. this kickstarts the
2957                                 // other side, waiting in WAIT_AUTH_2 state,
2958                                 // into starting their burst, as it shows
2959                                 // that we're happy.
2960                                 this->LinkState = CONNECTED;
2961                                 // we should add the details of this server now
2962                                 // to the servers tree, as a child of the root
2963                                 // node.
2964                                 TreeServer* Node = new TreeServer(this->Utils,this->Instance,sname,description,Utils->TreeRoot,this);
2965                                 Utils->TreeRoot->AddChild(Node);
2966                                 params[3] = ":" + params[3];
2967                                 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,sname);
2968                                 this->bursting = true;
2969                                 this->DoBurst(Node);
2970                                 return true;
2971                         }
2972                 }
2973                 this->WriteLine("ERROR :Invalid credentials");
2974                 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
2975                 return false;
2976         }
2977
2978         bool Inbound_Server(std::deque<std::string> &params)
2979         {
2980                 if (params.size() < 4)
2981                         return false;
2982
2983                 irc::string servername = params[0].c_str();
2984                 std::string sname = params[0];
2985                 std::string password = params[1];
2986                 int hops = atoi(params[2].c_str());
2987
2988                 if (hops)
2989                 {
2990                         this->WriteLine("ERROR :Server too far away for authentication");
2991                         this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2992                         return false;
2993                 }
2994                 std::string description = params[3];
2995                 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
2996                 {
2997                         if ((x->Name == servername) && (x->RecvPass == password))
2998                         {
2999                                 TreeServer* CheckDupe = Utils->FindServer(sname);
3000                                 if (CheckDupe)
3001                                 {
3002                                         this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
3003                                         this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
3004                                         return false;
3005                                 }
3006                                 /* If the config says this link is encrypted, but the remote side
3007                                  * hasnt bothered to send the AES command before SERVER, then we
3008                                  * boot them off as we MUST have this connection encrypted.
3009                                  */
3010                                 if ((x->EncryptionKey != "") && (!this->ctx_in))
3011                                 {
3012                                         this->WriteLine("ERROR :This link requires AES encryption to be enabled. Plaintext connection refused.");
3013                                         this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, remote server did not enable AES.");
3014                                         return false;
3015                                 }
3016                                 this->Instance->SNO->WriteToSnoMask('l',"Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
3017                                 this->InboundServerName = sname;
3018                                 this->InboundDescription = description;
3019                                 // this is good. Send our details: Our server name and description and hopcount of 0,
3020                                 // along with the sendpass from this block.
3021                                 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+x->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
3022                                 // move to the next state, we are now waiting for THEM.
3023                                 this->LinkState = WAIT_AUTH_2;
3024                                 return true;
3025                         }
3026                 }
3027                 this->WriteLine("ERROR :Invalid credentials");
3028                 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
3029                 return false;
3030         }
3031
3032         void Split(const std::string &line, std::deque<std::string> &n)
3033         {
3034                 n.clear();
3035                 irc::tokenstream tokens(line);
3036                 std::string param;
3037                 while ((param = tokens.GetToken()) != "")
3038                         n.push_back(param);
3039                 return;
3040         }
3041
3042         bool ProcessLine(std::string &line)
3043         {
3044                 std::deque<std::string> params;
3045                 irc::string command;
3046                 std::string prefix;
3047                 
3048                 if (line.empty())
3049                         return true;
3050                 
3051                 line = line.substr(0, line.find_first_of("\r\n"));
3052                 
3053                 Instance->Log(DEBUG,"IN: %s", line.c_str());
3054                 
3055                 this->Split(line.c_str(),params);
3056                         
3057                 if ((params[0][0] == ':') && (params.size() > 1))
3058                 {
3059                         prefix = params[0].substr(1);
3060                         params.pop_front();
3061                 }
3062
3063                 command = params[0].c_str();
3064                 params.pop_front();
3065
3066                 if ((!this->ctx_in) && (command == "AES"))
3067                 {
3068                         std::string sserv = params[0];
3069                         for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
3070                         {
3071                                 if ((x->EncryptionKey != "") && (x->Name == sserv))
3072                                 {
3073                                         this->InitAES(x->EncryptionKey,sserv);
3074                                 }
3075                         }
3076
3077                         return true;
3078                 }
3079                 else if ((this->ctx_in) && (command == "AES"))
3080                 {
3081                         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());
3082                 }
3083
3084                 switch (this->LinkState)
3085                 {
3086                         TreeServer* Node;
3087                         
3088                         case WAIT_AUTH_1:
3089                                 // Waiting for SERVER command from remote server. Server initiating
3090                                 // the connection sends the first SERVER command, listening server
3091                                 // replies with theirs if its happy, then if the initiator is happy,
3092                                 // it starts to send its net sync, which starts the merge, otherwise
3093                                 // it sends an ERROR.
3094                                 if (command == "PASS")
3095                                 {
3096                                         /* Silently ignored */
3097                                 }
3098                                 else if (command == "SERVER")
3099                                 {
3100                                         return this->Inbound_Server(params);
3101                                 }
3102                                 else if (command == "ERROR")
3103                                 {
3104                                         return this->Error(params);
3105                                 }
3106                                 else if (command == "USER")
3107                                 {
3108                                         this->WriteLine("ERROR :Client connections to this port are prohibited.");
3109                                         return false;
3110                                 }
3111                                 else if (command == "CAPAB")
3112                                 {
3113                                         return this->Capab(params);
3114                                 }
3115                                 else if ((command == "U") || (command == "S"))
3116                                 {
3117                                         this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
3118                                         return false;
3119                                 }
3120                                 else
3121                                 {
3122                                         std::string error("ERROR :Invalid command in negotiation phase: ");
3123                                         error.append(command.c_str());
3124                                         this->WriteLine(error);
3125                                         return false;
3126                                 }
3127                         break;
3128                         case WAIT_AUTH_2:
3129                                 // Waiting for start of other side's netmerge to say they liked our
3130                                 // password.
3131                                 if (command == "SERVER")
3132                                 {
3133                                         // cant do this, they sent it to us in the WAIT_AUTH_1 state!
3134                                         // silently ignore.
3135                                         return true;
3136                                 }
3137                                 else if ((command == "U") || (command == "S"))
3138                                 {
3139                                         this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
3140                                         return false;
3141                                 }
3142                                 else if (command == "BURST")
3143                                 {
3144                                         if (params.size() && Utils->EnableTimeSync)
3145                                         {
3146                                                 /* If a time stamp is provided, apply synchronization */
3147                                                 bool force = false;
3148                                                 time_t them = atoi(params[0].c_str());
3149                                                 time_t us = Instance->Time(true);
3150                                                 int delta = them - us;
3151
3152                                                 if ((params.size() == 2) && (params[1] == "FORCE"))
3153                                                         force = true;
3154
3155                                                 if ((delta < -600) || (delta > 600))
3156                                                 {
3157                                                         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));
3158                                                         this->WriteLine("ERROR :Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than ten minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
3159                                                         return false;
3160                                                 }
3161                                                 
3162                                                 if (us == them)
3163                                                 {
3164                                                         this->Instance->Log(DEBUG, "Timestamps are equal; pat yourself on the back");
3165                                                 }
3166                                                 else if (force || (us > them))
3167                                                 {
3168                                                         this->Instance->Log(DEBUG, "Remote server has lower TS (%d seconds)", them - us);
3169                                                         this->Instance->SetTimeDelta(them - us);
3170                                                         // Send this new timestamp to any other servers
3171                                                         Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
3172                                                 }
3173                                                 else
3174                                                 {
3175                                                         // Override the timestamp
3176                                                         this->Instance->Log(DEBUG, "We have a higher timestamp (by %d seconds), not updating delta", us - them);
3177                                                         this->WriteLine(":" + Utils->TreeRoot->GetName() + " TIMESET " + ConvToStr(us));
3178                                                 }
3179                                         }
3180                                         this->LinkState = CONNECTED;
3181                                         Node = new TreeServer(this->Utils,this->Instance,InboundServerName,InboundDescription,Utils->TreeRoot,this);
3182                                         Utils->TreeRoot->AddChild(Node);
3183                                         params.clear();
3184                                         params.push_back(InboundServerName);
3185                                         params.push_back("*");
3186                                         params.push_back("1");
3187                                         params.push_back(":"+InboundDescription);
3188                                         Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,InboundServerName);
3189                                         this->bursting = true;
3190                                         this->DoBurst(Node);
3191                                 }
3192                                 else if (command == "ERROR")
3193                                 {
3194                                         return this->Error(params);
3195                                 }
3196                                 else if (command == "CAPAB")
3197                                 {
3198                                         return this->Capab(params);
3199                                 }
3200                                 
3201                         break;
3202                         case LISTENER:
3203                                 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
3204                                 return false;
3205                         break;
3206                         case CONNECTING:
3207                                 if (command == "SERVER")
3208                                 {
3209                                         // another server we connected to, which was in WAIT_AUTH_1 state,
3210                                         // has just sent us their credentials. If we get this far, theyre
3211                                         // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
3212                                         // if we're happy with this, we should send our netburst which
3213                                         // kickstarts the merge.
3214                                         return this->Outbound_Reply_Server(params);
3215                                 }
3216                                 else if (command == "ERROR")
3217                                 {
3218                                         return this->Error(params);
3219                                 }
3220                         break;
3221                         case CONNECTED:
3222                                 // This is the 'authenticated' state, when all passwords
3223                                 // have been exchanged and anything past this point is taken
3224                                 // as gospel.
3225                                 
3226                                 if (prefix != "")
3227                                 {
3228                                         std::string direction = prefix;
3229                                         userrec* t = this->Instance->FindNick(prefix);
3230                                         if (t)
3231                                         {
3232                                                 direction = t->server;
3233                                         }
3234                                         TreeServer* route_back_again = Utils->BestRouteTo(direction);
3235                                         if ((!route_back_again) || (route_back_again->GetSocket() != this))
3236                                         {
3237                                                 if (route_back_again)
3238                                                         Instance->Log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
3239                                                 return true;
3240                                         }
3241
3242                                         /* Fix by brain:
3243                                          * When there is activity on the socket, reset the ping counter so
3244                                          * that we're not wasting bandwidth pinging an active server.
3245                                          */ 
3246                                         route_back_again->SetNextPingTime(time(NULL) + 60);
3247                                         route_back_again->SetPingFlag();
3248                                 }
3249                                 
3250                                 if (command == "SVSMODE")
3251                                 {
3252                                         /* Services expects us to implement
3253                                          * SVSMODE. In inspircd its the same as
3254                                          * MODE anyway.
3255                                          */
3256                                         command = "MODE";
3257                                 }
3258                                 std::string target = "";
3259                                 /* Yes, know, this is a mess. Its reasonably fast though as we're
3260                                  * working with std::string here.
3261                                  */
3262                                 if ((command == "NICK") && (params.size() > 1))
3263                                 {
3264                                         return this->IntroduceClient(prefix,params);
3265                                 }
3266                                 else if (command == "FJOIN")
3267                                 {
3268                                         return this->ForceJoin(prefix,params);
3269                                 }
3270                                 else if (command == "STATS")
3271                                 {
3272                                         return this->Stats(prefix, params);
3273                                 }
3274                                 else if (command == "MOTD")
3275                                 {
3276                                         return this->Motd(prefix, params);
3277                                 }
3278                                 else if (command == "ADMIN")
3279                                 {
3280                                         return this->Admin(prefix, params);
3281                                 }
3282                                 else if (command == "SERVER")
3283                                 {
3284                                         return this->RemoteServer(prefix,params);
3285                                 }
3286                                 else if (command == "ERROR")
3287                                 {
3288                                         return this->Error(params);
3289                                 }
3290                                 else if (command == "OPERTYPE")
3291                                 {
3292                                         return this->OperType(prefix,params);
3293                                 }
3294                                 else if (command == "FMODE")
3295                                 {
3296                                         return this->ForceMode(prefix,params);
3297                                 }
3298                                 else if (command == "KILL")
3299                                 {
3300                                         return this->RemoteKill(prefix,params);
3301                                 }
3302                                 else if (command == "FTOPIC")
3303                                 {
3304                                         return this->ForceTopic(prefix,params);
3305                                 }
3306                                 else if (command == "REHASH")
3307                                 {
3308                                         return this->RemoteRehash(prefix,params);
3309                                 }
3310                                 else if (command == "METADATA")
3311                                 {
3312                                         return this->MetaData(prefix,params);
3313                                 }
3314                                 else if (command == "REMSTATUS")
3315                                 {
3316                                         return this->RemoveStatus(prefix,params);
3317                                 }
3318                                 else if (command == "PING")
3319                                 {
3320                                         /*
3321                                          * We just got a ping from a server that's bursting.
3322                                          * This can't be right, so set them to not bursting, and
3323                                          * apply their lines.
3324                                          */
3325                                         if (this->bursting)
3326                                         {
3327                                                 this->bursting = false;
3328                                                 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3329                                         }
3330                                         if (prefix == "")
3331                                         {
3332                                                 prefix = this->GetName();
3333                                         }
3334                                         return this->LocalPing(prefix,params);
3335                                 }
3336                                 else if (command == "PONG")
3337                                 {
3338                                         /*
3339                                          * We just got a pong from a server that's bursting.
3340                                          * This can't be right, so set them to not bursting, and
3341                                          * apply their lines.
3342                                          */
3343                                         if (this->bursting)
3344                                         {
3345                                                 this->bursting = false;
3346                                                 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3347                                         }
3348                                         if (prefix == "")
3349                                         {
3350                                                 prefix = this->GetName();
3351                                         }
3352                                         return this->LocalPong(prefix,params);
3353                                 }
3354                                 else if (command == "VERSION")
3355                                 {
3356                                         return this->ServerVersion(prefix,params);
3357                                 }
3358                                 else if (command == "FHOST")
3359                                 {
3360                                         return this->ChangeHost(prefix,params);
3361                                 }
3362                                 else if (command == "FNAME")
3363                                 {
3364                                         return this->ChangeName(prefix,params);
3365                                 }
3366                                 else if (command == "ADDLINE")
3367                                 {
3368                                         return this->AddLine(prefix,params);
3369                                 }
3370                                 else if (command == "SVSNICK")
3371                                 {
3372                                         if (prefix == "")
3373                                         {
3374                                                 prefix = this->GetName();
3375                                         }
3376                                         return this->ForceNick(prefix,params);
3377                                 }
3378                                 else if (command == "IDLE")
3379                                 {
3380                                         return this->Whois(prefix,params);
3381                                 }
3382                                 else if (command == "PUSH")
3383                                 {
3384                                         return this->Push(prefix,params);
3385                                 }
3386                                 else if (command == "TIMESET")
3387                                 {
3388                                         return this->HandleSetTime(prefix, params);
3389                                 }
3390                                 else if (command == "TIME")
3391                                 {
3392                                         return this->Time(prefix,params);
3393                                 }
3394                                 else if ((command == "KICK") && (Utils->IsServer(prefix)))
3395                                 {
3396                                         std::string sourceserv = this->myhost;
3397                                         if (params.size() == 3)
3398                                         {
3399                                                 userrec* user = this->Instance->FindNick(params[1]);
3400                                                 chanrec* chan = this->Instance->FindChan(params[0]);
3401                                                 if (user && chan)
3402                                                 {
3403                                                         if (!chan->ServerKickUser(user, params[2].c_str(), false))
3404                                                                 /* Yikes, the channels gone! */
3405                                                                 delete chan;
3406                                                 }
3407                                         }
3408                                         if (this->InboundServerName != "")
3409                                         {
3410                                                 sourceserv = this->InboundServerName;
3411                                         }
3412                                         return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3413                                 }
3414                                 else if (command == "SVSJOIN")
3415                                 {
3416                                         if (prefix == "")
3417                                         {
3418                                                 prefix = this->GetName();
3419                                         }
3420                                         return this->ServiceJoin(prefix,params);
3421                                 }
3422                                 else if (command == "SQUIT")
3423                                 {
3424                                         if (params.size() == 2)
3425                                         {
3426                                                 this->Squit(Utils->FindServer(params[0]),params[1]);
3427                                         }
3428                                         return true;
3429                                 }
3430                                 else if (command == "OPERNOTICE")
3431                                 {
3432                                         std::string sourceserv = this->myhost;
3433
3434                                         if (this->InboundServerName != "")
3435                                                 sourceserv = this->InboundServerName;
3436
3437                                         if (params.size() >= 1)
3438                                                 Instance->WriteOpers("*** From " + sourceserv + ": " + params[0]);
3439
3440                                         return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
3441                                 }
3442                                 else if (command == "MODENOTICE")
3443                                 {
3444                                         std::string sourceserv = this->myhost;
3445                                         if (this->InboundServerName != "")
3446                                                 sourceserv = this->InboundServerName;
3447                                         if (params.size() >= 2)
3448                                         {
3449                                                 Instance->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s", sourceserv.c_str(), params[1].c_str());
3450                                         }
3451
3452                                         return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
3453                                 }
3454                                 else if (command == "SNONOTICE")
3455                                 {
3456                                         std::string sourceserv = this->myhost;
3457                                         if (this->InboundServerName != "")
3458                                                 sourceserv = this->InboundServerName;
3459                                         if (params.size() >= 2)
3460                                         {
3461                                                 Instance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + sourceserv + ": "+ params[1]);
3462                                         }
3463
3464                                         return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
3465                                 }
3466                                 else if (command == "ENDBURST")
3467                                 {
3468                                         this->bursting = false;
3469                                         Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3470                                         std::string sourceserv = this->myhost;
3471                                         if (this->InboundServerName != "")
3472                                         {
3473                                                 sourceserv = this->InboundServerName;
3474                                         }
3475                                         this->Instance->SNO->WriteToSnoMask('l',"Received end of netburst from \2%s\2",sourceserv.c_str());
3476
3477                                         Event rmode((char*)sourceserv.c_str(), (Module*)Utils->Creator, "new_server");
3478                                         rmode.Send(Instance);
3479
3480                                         return true;
3481                                 }
3482                                 else
3483                                 {
3484                                         // not a special inter-server command.
3485                                         // Emulate the actual user doing the command,
3486                                         // this saves us having a huge ugly parser.
3487                                         userrec* who = this->Instance->FindNick(prefix);
3488                                         std::string sourceserv = this->myhost;
3489                                         if (this->InboundServerName != "")
3490                                         {
3491                                                 sourceserv = this->InboundServerName;
3492                                         }
3493                                         if ((!who) && (command == "MODE"))
3494                                         {
3495                                                 if (Utils->IsServer(prefix))
3496                                                 {
3497                                                         const char* modelist[127];
3498                                                         for (size_t i = 0; i < params.size(); i++)
3499                                                                 modelist[i] = params[i].c_str();
3500
3501                                                         userrec* fake = new userrec(Instance);
3502                                                         fake->SetFd(FD_MAGIC_NUMBER);
3503
3504                                                         this->Instance->SendMode(modelist, params.size(), fake);
3505         
3506                                                         delete fake;
3507
3508                                                         /* Hot potato! pass it on! */
3509                                                         return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3510                                                 }
3511                                         }
3512                                         if (who)
3513                                         {
3514                                                 if ((command == "NICK") && (params.size() > 0))
3515                                                 {
3516                                                         /* On nick messages, check that the nick doesnt
3517                                                          * already exist here. If it does, kill their copy,
3518                                                          * and our copy.
3519                                                          */
3520                                                         userrec* x = this->Instance->FindNick(params[0]);
3521                                                         if ((x) && (x != who))
3522                                                         {
3523                                                                 std::deque<std::string> p;
3524                                                                 p.push_back(params[0]);
3525                                                                 p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
3526                                                                 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
3527                                                                 p.clear();
3528                                                                 p.push_back(prefix);
3529                                                                 p.push_back("Nickname collision");
3530                                                                 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
3531                                                                 userrec::QuitUser(this->Instance,x,"Nickname collision ("+prefix+" -> "+params[0]+")");
3532                                                                 userrec* y = this->Instance->FindNick(prefix);
3533                                                                 if (y)
3534                                                                 {
3535                                                                         userrec::QuitUser(this->Instance,y,"Nickname collision");
3536                                                                 }
3537                                                                 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3538                                                         }
3539                                                 }
3540                                                 // its a user
3541                                                 target = who->server;
3542                                                 const char* strparams[127];
3543                                                 for (unsigned int q = 0; q < params.size(); q++)
3544                                                 {
3545                                                         strparams[q] = params[q].c_str();
3546                                                 }
3547                                                 switch (this->Instance->CallCommandHandler(command.c_str(), strparams, params.size(), who))
3548                                                 {
3549                                                         case CMD_INVALID:
3550                                                                 this->WriteLine("ERROR :Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
3551                                                                 return false;
3552                                                         break;
3553                                                         case CMD_FAILURE:
3554                                                                 return true;
3555                                                         break;
3556                                                         default:
3557                                                                 /* CMD_SUCCESS and CMD_USER_DELETED fall through here */
3558                                                         break;
3559                                                 }
3560                                         }
3561                                         else
3562                                         {
3563                                                 // its not a user. Its either a server, or somethings screwed up.
3564                                                 if (Utils->IsServer(prefix))
3565                                                 {
3566                                                         target = this->Instance->Config->ServerName;
3567                                                 }
3568                                                 else
3569                                                 {
3570                                                         Instance->Log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
3571                                                         return true;
3572                                                 }
3573                                         }
3574                                         return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3575
3576                                 }
3577                                 return true;
3578                         break;
3579                 }
3580                 return true;
3581         }
3582
3583         virtual std::string GetName()
3584         {
3585                 std::string sourceserv = this->myhost;
3586                 if (this->InboundServerName != "")
3587                 {
3588                         sourceserv = this->InboundServerName;
3589                 }
3590                 return sourceserv;
3591         }
3592
3593         virtual void OnTimeout()
3594         {
3595                 if (this->LinkState == CONNECTING)
3596                 {
3597                         this->Instance->SNO->WriteToSnoMask('l',"CONNECT: Connection to \002"+myhost+"\002 timed out.");
3598                         Link* MyLink = Utils->FindLink(myhost);
3599                         if (MyLink)
3600                                 Utils->DoFailOver(MyLink);
3601                 }
3602         }
3603
3604         virtual void OnClose()
3605         {
3606                 // Connection closed.
3607                 // If the connection is fully up (state CONNECTED)
3608                 // then propogate a netsplit to all peers.
3609                 std::string quitserver = this->myhost;
3610                 if (this->InboundServerName != "")
3611                 {
3612                         quitserver = this->InboundServerName;
3613                 }
3614                 TreeServer* s = Utils->FindServer(quitserver);
3615                 if (s)
3616                 {
3617                         Squit(s,"Remote host closed the connection");
3618                 }
3619
3620                 if (quitserver != "")
3621                         this->Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' failed.",quitserver.c_str());
3622         }
3623
3624         virtual int OnIncomingConnection(int newsock, char* ip)
3625         {
3626                 /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
3627                  * or discovering if this port is the server port, we don't allow connections from any
3628                  * IPs for which we don't have a link block.
3629                  */
3630                 bool found = false;
3631
3632                 found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());
3633                 if (!found)
3634                 {
3635                         for (vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
3636                                 if (irc::sockets::MatchCIDR(ip, (*i).c_str()))
3637                                         found = true;
3638
3639                         if (!found)
3640                         {
3641                                 this->Instance->SNO->WriteToSnoMask('l',"Server connection from %s denied (no link blocks with that IP address)", ip);
3642                                 close(newsock);
3643                                 return false;
3644                         }
3645                 }
3646                 TreeSocket* s = new TreeSocket(this->Utils, this->Instance, newsock, ip);
3647                 s = s; /* Whinge whinge whinge, thats all GCC ever does. */
3648                 return true;
3649         }
3650 };
3651
3652 /** This class is used to resolve server hostnames during /connect and autoconnect.
3653  * As of 1.1, the resolver system is seperated out from InspSocket, so we must do this
3654  * resolver step first ourselves if we need it. This is totally nonblocking, and will
3655  * callback to OnLookupComplete or OnError when completed. Once it has completed we
3656  * will have an IP address which we can then use to continue our connection.
3657  */
3658 class ServernameResolver : public Resolver
3659 {       
3660  private:
3661         /** A copy of the Link tag info for what we're connecting to.
3662          * We take a copy, rather than using a pointer, just in case the
3663          * admin takes the tag away and rehashes while the domain is resolving.
3664          */
3665         Link MyLink;
3666         SpanningTreeUtilities* Utils;
3667  public: 
3668         ServernameResolver(Module* me, SpanningTreeUtilities* Util, InspIRCd* Instance, const std::string &hostname, Link x) : Resolver(Instance, hostname, DNS_QUERY_FORWARD, me), MyLink(x), Utils(Util)
3669         {
3670                 /* Nothing in here, folks */
3671         }
3672
3673         void OnLookupComplete(const std::string &result)
3674         {
3675                 /* Initiate the connection, now that we have an IP to use.
3676                  * Passing a hostname directly to InspSocket causes it to
3677                  * just bail and set its FD to -1.
3678                  */
3679                 TreeServer* CheckDupe = Utils->FindServer(MyLink.Name.c_str());
3680                 if (!CheckDupe) /* Check that nobody tried to connect it successfully while we were resolving */
3681                 {
3682                         TreeSocket* newsocket = new TreeSocket(this->Utils, ServerInstance, result,MyLink.Port,false,MyLink.Timeout ? MyLink.Timeout : 10,MyLink.Name.c_str());
3683                         if (newsocket->GetFd() > -1)
3684                         {
3685                                 /* We're all OK */
3686                         }
3687                         else
3688                         {
3689                                 /* Something barfed, show the opers */
3690                                 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",MyLink.Name.c_str(),strerror(errno));
3691                                 delete newsocket;
3692                                 Utils->DoFailOver(&MyLink);
3693                         }
3694                 }
3695         }
3696
3697         void OnError(ResolverError e, const std::string &errormessage)
3698         {
3699                 /* Ooops! */
3700                 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: Unable to resolve hostname - %s",MyLink.Name.c_str(),errormessage.c_str());
3701                 Utils->DoFailOver(&MyLink);
3702         }
3703 };
3704
3705 /** Handle resolving of server IPs for the cache
3706  */
3707 class SecurityIPResolver : public Resolver
3708 {
3709  private:
3710         Link MyLink;
3711         SpanningTreeUtilities* Utils;
3712  public:
3713         SecurityIPResolver(Module* me, SpanningTreeUtilities* U, InspIRCd* Instance, const std::string &hostname, Link x) : Resolver(Instance, hostname, DNS_QUERY_FORWARD, me), MyLink(x), Utils(U)
3714         {
3715         }
3716
3717         void OnLookupComplete(const std::string &result)
3718         {
3719                 ServerInstance->Log(DEBUG,"Security IP cache: Adding IP address '%s' for Link '%s'",result.c_str(),MyLink.Name.c_str());
3720                 Utils->ValidIPs.push_back(result);
3721         }
3722
3723         void OnError(ResolverError e, const std::string &errormessage)
3724         {
3725                 ServerInstance->Log(DEBUG,"Could not resolve IP associated with Link '%s': %s",MyLink.Name.c_str(),errormessage.c_str());
3726         }
3727 };
3728
3729 SpanningTreeUtilities::SpanningTreeUtilities(InspIRCd* Instance, ModuleSpanningTree* C) : ServerInstance(Instance), Creator(C)
3730 {
3731         Bindings.clear();
3732         this->ReadConfiguration(true);
3733         this->TreeRoot = new TreeServer(this, ServerInstance, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc);
3734 }
3735
3736 SpanningTreeUtilities::~SpanningTreeUtilities()
3737 {
3738         for (unsigned int i = 0; i < Bindings.size(); i++)
3739         {
3740                 ServerInstance->Log(DEBUG,"Freeing binding %d of %d",i, Bindings.size());
3741                 ServerInstance->SE->DelFd(Bindings[i]);
3742                 Bindings[i]->Close();
3743                 DELETE(Bindings[i]);
3744         }
3745         ServerInstance->Log(DEBUG,"Freeing connected servers...");
3746         while (TreeRoot->ChildCount())
3747         {
3748                 TreeServer* child_server = TreeRoot->GetChild(0);
3749                 ServerInstance->Log(DEBUG,"Freeing connected server %s", child_server->GetName().c_str());
3750                 if (child_server)
3751                 {
3752                         TreeSocket* sock = child_server->GetSocket();
3753                         ServerInstance->SE->DelFd(sock);
3754                         sock->Close();
3755                         DELETE(sock);
3756                 }
3757         }
3758         delete TreeRoot;
3759 }
3760
3761 void SpanningTreeUtilities::AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
3762 {
3763         for (unsigned int c = 0; c < list.size(); c++)
3764         {
3765                 if (list[c] == server)
3766                 {
3767                         return;
3768                 }
3769         }
3770         list.push_back(server);
3771 }
3772
3773 /** returns a list of DIRECT servernames for a specific channel */
3774 void SpanningTreeUtilities::GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
3775 {
3776         CUList *ulist = c->GetUsers();
3777         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
3778         {
3779                 if (i->second->GetFd() < 0)
3780                 {
3781                         TreeServer* best = this->BestRouteTo(i->second->server);
3782                         if (best)
3783                                 AddThisServer(best,list);
3784                 }
3785         }
3786         return;
3787 }
3788
3789 bool SpanningTreeUtilities::DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, std::deque<std::string> &params)
3790 {
3791         TreeServer* omitroute = this->BestRouteTo(omit);
3792         if ((command == "NOTICE") || (command == "PRIVMSG"))
3793         {
3794                 if (params.size() >= 2)
3795                 {
3796                         /* Prefixes */
3797                         if ((*(params[0].c_str()) == '@') || (*(params[0].c_str()) == '%') || (*(params[0].c_str()) == '+'))
3798                         {
3799                                 params[0] = params[0].substr(1, params[0].length()-1);
3800                         }
3801                         if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$'))
3802                         {
3803                                 // special routing for private messages/notices
3804                                 userrec* d = ServerInstance->FindNick(params[0]);
3805                                 if (d)
3806                                 {
3807                                         std::deque<std::string> par;
3808                                         par.push_back(params[0]);
3809                                         par.push_back(":"+params[1]);
3810                                         this->DoOneToOne(prefix,command.c_str(),par,d->server);
3811                                         return true;
3812                                 }
3813                         }
3814                         else if (*(params[0].c_str()) == '$')
3815                         {
3816                                 std::deque<std::string> par;
3817                                 par.push_back(params[0]);
3818                                 par.push_back(":"+params[1]);
3819                                 this->DoOneToAllButSender(prefix,command.c_str(),par,omitroute->GetName());
3820                                 return true;
3821                         }
3822                         else
3823                         {
3824                                 chanrec* c = ServerInstance->FindChan(params[0]);
3825                                 if (c)
3826                                 {
3827                                         std::deque<TreeServer*> list;
3828                                         GetListOfServersForChannel(c,list);
3829                                         unsigned int lsize = list.size();
3830                                         for (unsigned int i = 0; i < lsize; i++)
3831                                         {
3832                                                 TreeSocket* Sock = list[i]->GetSocket();
3833                                                 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
3834                                                 {
3835                                                         Sock->WriteLine(data);
3836                                                 }
3837                                         }
3838                                         return true;
3839                                 }
3840                         }
3841                 }
3842         }
3843         unsigned int items =this->TreeRoot->ChildCount();
3844         for (unsigned int x = 0; x < items; x++)
3845         {
3846                 TreeServer* Route = this->TreeRoot->GetChild(x);
3847                 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3848                 {
3849                         TreeSocket* Sock = Route->GetSocket();
3850                         if (Sock)
3851                                 Sock->WriteLine(data);
3852                 }
3853         }
3854         return true;
3855 }
3856
3857 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, std::deque<std::string> &params, std::string omit)
3858 {
3859         TreeServer* omitroute = this->BestRouteTo(omit);
3860         std::string FullLine = ":" + prefix + " " + command;
3861         unsigned int words = params.size();
3862         for (unsigned int x = 0; x < words; x++)
3863         {
3864                 FullLine = FullLine + " " + params[x];
3865         }
3866         unsigned int items = this->TreeRoot->ChildCount();
3867         for (unsigned int x = 0; x < items; x++)
3868         {
3869                 TreeServer* Route = this->TreeRoot->GetChild(x);
3870                 // Send the line IF:
3871                 // The route has a socket (its a direct connection)
3872                 // The route isnt the one to be omitted
3873                 // The route isnt the path to the one to be omitted
3874                 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3875                 {
3876                         TreeSocket* Sock = Route->GetSocket();
3877                         if (Sock)
3878                                 Sock->WriteLine(FullLine);
3879                 }
3880         }
3881         return true;
3882 }
3883
3884 bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, std::deque<std::string> &params)
3885 {
3886         std::string FullLine = ":" + prefix + " " + command;
3887         unsigned int words = params.size();
3888         for (unsigned int x = 0; x < words; x++)
3889         {
3890                 FullLine = FullLine + " " + params[x];
3891         }
3892         unsigned int items = this->TreeRoot->ChildCount();
3893         for (unsigned int x = 0; x < items; x++)
3894         {
3895                 TreeServer* Route = this->TreeRoot->GetChild(x);
3896                 if (Route && Route->GetSocket())
3897                 {
3898                         TreeSocket* Sock = Route->GetSocket();
3899                         if (Sock)
3900                                 Sock->WriteLine(FullLine);
3901                 }
3902         }
3903         return true;
3904 }
3905
3906 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, std::deque<std::string> &params)
3907 {
3908         std::string spfx = prefix;
3909         std::string scmd = command;
3910         return this->DoOneToMany(spfx, scmd, params);
3911 }
3912
3913 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> &params, std::string omit)
3914 {
3915         std::string spfx = prefix;
3916         std::string scmd = command;
3917         return this->DoOneToAllButSender(spfx, scmd, params, omit);
3918 }
3919         
3920 bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, std::deque<std::string> &params, std::string target)
3921 {
3922         TreeServer* Route = this->BestRouteTo(target);
3923         if (Route)
3924         {
3925                 std::string FullLine = ":" + prefix + " " + command;
3926                 unsigned int words = params.size();
3927                 for (unsigned int x = 0; x < words; x++)
3928                 {
3929                         FullLine = FullLine + " " + params[x];
3930                 }
3931                 if (Route && Route->GetSocket())
3932                 {
3933                         TreeSocket* Sock = Route->GetSocket();
3934                         if (Sock)
3935                                 Sock->WriteLine(FullLine);
3936                 }
3937                 return true;
3938         }
3939         else
3940         {
3941                 return false;
3942         }
3943 }
3944
3945 void SpanningTreeUtilities::ReadConfiguration(bool rebind)
3946 {
3947         ConfigReader* Conf = new ConfigReader(ServerInstance);
3948         if (rebind)
3949         {
3950                 for (int j =0; j < Conf->Enumerate("bind"); j++)
3951                 {
3952                         std::string Type = Conf->ReadValue("bind","type",j);
3953                         std::string IP = Conf->ReadValue("bind","address",j);
3954                         std::string Port = Conf->ReadValue("bind","port",j);
3955                         if (Type == "servers")
3956                         {
3957                                 irc::portparser portrange(Port, false);
3958                                 int portno = -1;
3959                                 while ((portno = portrange.GetToken()))
3960                                 {
3961                                         ServerInstance->Log(DEBUG,"m_spanningtree: Binding server port %s:%d", IP.c_str(), portno);
3962                                         if (IP == "*")
3963                                                 IP = "";
3964
3965                                         TreeSocket* listener = new TreeSocket(this, ServerInstance, IP.c_str(), portno, true, 10);
3966                                         if (listener->GetState() == I_LISTENING)
3967                                         {
3968                                                 ServerInstance->Log(DEFAULT,"m_spanningtree: Binding server port %s:%d successful!", IP.c_str(), portno);
3969                                                 Bindings.push_back(listener);
3970                                         }
3971                                         else
3972                                         {
3973                                                 ServerInstance->Log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %s:%d",IP.c_str(), portno);
3974                                                 listener->Close();
3975                                                 DELETE(listener);
3976                                         }
3977                                         ServerInstance->Log(DEBUG,"Done with this binding");
3978                                 }
3979                         }
3980                 }
3981         }
3982         FlatLinks = Conf->ReadFlag("options","flatlinks",0);
3983         HideULines = Conf->ReadFlag("options","hideulines",0);
3984         AnnounceTSChange = Conf->ReadFlag("options","announcets",0);
3985         EnableTimeSync = !(Conf->ReadFlag("options","notimesync",0));
3986         LinkBlocks.clear();
3987         ValidIPs.clear();
3988         for (int j =0; j < Conf->Enumerate("link"); j++)
3989         {
3990                 Link L;
3991                 std::string Allow = Conf->ReadValue("link","allowmask",j);
3992                 L.Name = (Conf->ReadValue("link","name",j)).c_str();
3993                 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
3994                 L.FailOver = Conf->ReadValue("link","failover",j).c_str();
3995                 L.Port = Conf->ReadInteger("link","port",j,true);
3996                 L.SendPass = Conf->ReadValue("link","sendpass",j);
3997                 L.RecvPass = Conf->ReadValue("link","recvpass",j);
3998                 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
3999                 L.EncryptionKey =  Conf->ReadValue("link","encryptionkey",j);
4000                 L.HiddenFromStats = Conf->ReadFlag("link","hidden",j);
4001                 L.Timeout = Conf->ReadInteger("link","timeout",j,true);
4002                 L.NextConnectTime = time(NULL) + L.AutoConnect;
4003                 /* Bugfix by brain, do not allow people to enter bad configurations */
4004                 if (L.Name != ServerInstance->Config->ServerName)
4005                 {
4006                         if ((L.IPAddr != "") && (L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
4007                         {
4008                                 ValidIPs.push_back(L.IPAddr);
4009
4010                                 if (Allow.length())
4011                                         ValidIPs.push_back(Allow);
4012
4013                                 /* Needs resolving */
4014                                 insp_inaddr binip;
4015                                 if (insp_aton(L.IPAddr.c_str(), &binip) < 1)
4016                                 {
4017                                         try
4018                                         {
4019                                                 SecurityIPResolver* sr = new SecurityIPResolver((Module*)this->Creator, this, ServerInstance, L.IPAddr, L);
4020                                                 ServerInstance->AddResolver(sr);
4021                                         }
4022                                         catch (ModuleException& e)
4023                                         {
4024                                                 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
4025                                         }
4026                                 }
4027
4028                                 LinkBlocks.push_back(L);
4029                                 ServerInstance->Log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
4030                         }
4031                         else
4032                         {
4033                                 if (L.IPAddr == "")
4034                                 {
4035                                         ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', IP address not defined!",L.Name.c_str());
4036                                 }
4037                                 else if (L.RecvPass == "")
4038                                 {
4039                                         ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', recvpass not defined!",L.Name.c_str());
4040                                 }
4041                                 else if (L.SendPass == "")
4042                                 {
4043                                         ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', sendpass not defined!",L.Name.c_str());
4044                                 }
4045                                 else if (L.Name == "")
4046                                 {
4047                                         ServerInstance->Log(DEFAULT,"Invalid configuration, link tag without a name!");
4048                                 }
4049                                 else if (!L.Port)
4050                                 {
4051                                         ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', no port specified!",L.Name.c_str());
4052                                 }
4053                         }
4054                 }
4055                 else
4056                 {
4057                         ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', link tag has the same server name as the local server!",L.Name.c_str());
4058                 }
4059         }
4060         DELETE(Conf);
4061 }
4062
4063 /** To create a timer which recurs every second, we inherit from InspTimer.
4064  * InspTimer is only one-shot however, so at the end of each Tick() we simply
4065  * insert another of ourselves into the pending queue :)
4066  */
4067 class TimeSyncTimer : public InspTimer
4068 {
4069  private:
4070         InspIRCd *Instance;
4071         ModuleSpanningTree *Module;
4072  public:
4073         TimeSyncTimer(InspIRCd *Instance, ModuleSpanningTree *Mod);
4074         virtual void Tick(time_t TIME);
4075 };
4076
4077 class ModuleSpanningTree : public Module
4078 {
4079         int line;
4080         int NumServers;
4081         unsigned int max_local;
4082         unsigned int max_global;
4083         cmd_rconnect* command_rconnect;
4084         SpanningTreeUtilities* Utils;
4085
4086  public:
4087         TimeSyncTimer *SyncTimer;
4088
4089         ModuleSpanningTree(InspIRCd* Me)
4090                 : Module::Module(Me), max_local(0), max_global(0)
4091         {
4092                 Utils = new SpanningTreeUtilities(Me, this);
4093
4094                 command_rconnect = new cmd_rconnect(ServerInstance, this, Utils);
4095                 ServerInstance->AddCommand(command_rconnect);
4096
4097                 if (Utils->EnableTimeSync)
4098                 {
4099                         SyncTimer = new TimeSyncTimer(ServerInstance, this);
4100                         ServerInstance->Timers->AddTimer(SyncTimer);
4101                 }
4102                 else
4103                         SyncTimer = NULL;
4104         }
4105
4106         void ShowLinks(TreeServer* Current, userrec* user, int hops)
4107         {
4108                 std::string Parent = Utils->TreeRoot->GetName();
4109                 if (Current->GetParent())
4110                 {
4111                         Parent = Current->GetParent()->GetName();
4112                 }
4113                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
4114                 {
4115                         if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str())))
4116                         {
4117                                 if (*user->oper)
4118                                 {
4119                                          ShowLinks(Current->GetChild(q),user,hops+1);
4120                                 }
4121                         }
4122                         else
4123                         {
4124                                 ShowLinks(Current->GetChild(q),user,hops+1);
4125                         }
4126                 }
4127                 /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
4128                 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetName().c_str())) && (!*user->oper))
4129                         return;
4130                 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());
4131         }
4132
4133         int CountLocalServs()
4134         {
4135                 return Utils->TreeRoot->ChildCount();
4136         }
4137
4138         int CountServs()
4139         {
4140                 return Utils->serverlist.size();
4141         }
4142
4143         void HandleLinks(const char** parameters, int pcnt, userrec* user)
4144         {
4145                 ShowLinks(Utils->TreeRoot,user,0);
4146                 user->WriteServ("365 %s * :End of /LINKS list.",user->nick);
4147                 return;
4148         }
4149
4150         void HandleLusers(const char** parameters, int pcnt, userrec* user)
4151         {
4152                 unsigned int n_users = ServerInstance->UserCount();
4153
4154                 /* Only update these when someone wants to see them, more efficient */
4155                 if ((unsigned int)ServerInstance->LocalUserCount() > max_local)
4156                         max_local = ServerInstance->LocalUserCount();
4157                 if (n_users > max_global)
4158                         max_global = n_users;
4159
4160                 unsigned int ulined_count = 0;
4161                 unsigned int ulined_local_count = 0;
4162
4163                 /* If ulined are hidden and we're not an oper, count the number of ulined servers hidden,
4164                  * locally and globally (locally means directly connected to us)
4165                  */
4166                 if ((Utils->HideULines) && (!*user->oper))
4167                 {
4168                         for (server_hash::iterator q = Utils->serverlist.begin(); q != Utils->serverlist.end(); q++)
4169                         {
4170                                 if (ServerInstance->ULine(q->second->GetName().c_str()))
4171                                 {
4172                                         ulined_count++;
4173                                         if (q->second->GetParent() == Utils->TreeRoot)
4174                                                 ulined_local_count++;
4175                                 }
4176                         }
4177                 }
4178
4179                 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());
4180                 if (ServerInstance->OperCount())
4181                         user->WriteServ("252 %s %d :operator(s) online",user->nick,ServerInstance->OperCount());
4182                 if (ServerInstance->UnregisteredUserCount())
4183                         user->WriteServ("253 %s %d :unknown connections",user->nick,ServerInstance->UnregisteredUserCount());
4184                 if (ServerInstance->ChannelCount())
4185                         user->WriteServ("254 %s %d :channels formed",user->nick,ServerInstance->ChannelCount());
4186                 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());
4187                 user->WriteServ("265 %s :Current Local Users: %d  Max: %d",user->nick,ServerInstance->LocalUserCount(),max_local);
4188                 user->WriteServ("266 %s :Current Global Users: %d  Max: %d",user->nick,n_users,max_global);
4189                 return;
4190         }
4191
4192         // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
4193
4194         void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80], float &totusers, float &totservers)
4195         {
4196                 if (line < 128)
4197                 {
4198                         for (int t = 0; t < depth; t++)
4199                         {
4200                                 matrix[line][t] = ' ';
4201                         }
4202
4203                         // For Aligning, we need to work out exactly how deep this thing is, and produce
4204                         // a 'Spacer' String to compensate.
4205                         char spacer[40];
4206
4207                         memset(spacer,' ',40);
4208                         if ((40 - Current->GetName().length() - depth) > 1) {
4209                                 spacer[40 - Current->GetName().length() - depth] = '\0';
4210                         }
4211                         else
4212                         {
4213                                 spacer[5] = '\0';
4214                         }
4215
4216                         float percent;
4217                         char text[80];
4218                         if (ServerInstance->clientlist.size() == 0) {
4219                                 // If there are no users, WHO THE HELL DID THE /MAP?!?!?!
4220                                 percent = 0;
4221                         }
4222                         else
4223                         {
4224                                 percent = ((float)Current->GetUserCount() / (float)ServerInstance->clientlist.size()) * 100;
4225                         }
4226                         snprintf(text, 80, "%s %s%5d [%5.2f%%]", Current->GetName().c_str(), spacer, Current->GetUserCount(), percent);
4227                         totusers += Current->GetUserCount();
4228                         totservers++;
4229                         strlcpy(&matrix[line][depth],text,80);
4230                         line++;
4231                         for (unsigned int q = 0; q < Current->ChildCount(); q++)
4232                         {
4233                                 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str())))
4234                                 {
4235                                         if (*user->oper)
4236                                         {
4237                                                 ShowMap(Current->GetChild(q),user,(Utils->FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
4238                                         }
4239                                 }
4240                                 else
4241                                 {
4242                                         ShowMap(Current->GetChild(q),user,(Utils->FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
4243                                 }
4244                         }
4245                 }
4246         }
4247
4248         int HandleMotd(const char** parameters, int pcnt, userrec* user)
4249         {
4250                 if (pcnt > 0)
4251                 {
4252                         /* Remote MOTD, the server is within the 1st parameter */
4253                         std::deque<std::string> params;
4254                         params.push_back(parameters[0]);
4255
4256                         /* Send it out remotely, generate no reply yet */
4257                         TreeServer* s = Utils->FindServerMask(parameters[0]);
4258                         if (s)
4259                         {
4260                                 Utils->DoOneToOne(user->nick, "MOTD", params, s->GetName());
4261                         }
4262                         else
4263                         {
4264                                 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4265                         }
4266                         return 1;
4267                 }
4268                 return 0;
4269         }
4270
4271         int HandleAdmin(const char** parameters, int pcnt, userrec* user)
4272         {
4273                 if (pcnt > 0)
4274                 {
4275                         /* Remote ADMIN, the server is within the 1st parameter */
4276                         std::deque<std::string> params;
4277                         params.push_back(parameters[0]);
4278
4279                         /* Send it out remotely, generate no reply yet */
4280                         TreeServer* s = Utils->FindServerMask(parameters[0]);
4281                         if (s)
4282                         {
4283                                 Utils->DoOneToOne(user->nick, "ADMIN", params, s->GetName());
4284                         }
4285                         else
4286                         {
4287                                 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4288                         }
4289                         return 1;
4290                 }
4291                 return 0;
4292         }
4293
4294         int HandleStats(const char** parameters, int pcnt, userrec* user)
4295         {
4296                 if (pcnt > 1)
4297                 {
4298                         /* Remote STATS, the server is within the 2nd parameter */
4299                         std::deque<std::string> params;
4300                         params.push_back(parameters[0]);
4301                         params.push_back(parameters[1]);
4302                         /* Send it out remotely, generate no reply yet */
4303                         TreeServer* s = Utils->FindServerMask(parameters[1]);
4304                         if (s)
4305                         {
4306                                 params[1] = s->GetName();
4307                                 Utils->DoOneToOne(user->nick, "STATS", params, s->GetName());
4308                         }
4309                         else
4310                         {
4311                                 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4312                         }
4313                         return 1;
4314                 }
4315                 return 0;
4316         }
4317
4318         // Ok, prepare to be confused.
4319         // After much mulling over how to approach this, it struck me that
4320         // the 'usual' way of doing a /MAP isnt the best way. Instead of
4321         // keeping track of a ton of ascii characters, and line by line
4322         // under recursion working out where to place them using multiplications
4323         // and divisons, we instead render the map onto a backplane of characters
4324         // (a character matrix), then draw the branches as a series of "L" shapes
4325         // from the nodes. This is not only friendlier on CPU it uses less stack.
4326
4327         void HandleMap(const char** parameters, int pcnt, userrec* user)
4328         {
4329                 // This array represents a virtual screen which we will
4330                 // "scratch" draw to, as the console device of an irc
4331                 // client does not provide for a proper terminal.
4332                 float totusers = 0;
4333                 float totservers = 0;
4334                 char matrix[128][80];
4335                 for (unsigned int t = 0; t < 128; t++)
4336                 {
4337                         matrix[t][0] = '\0';
4338                 }
4339                 line = 0;
4340                 // The only recursive bit is called here.
4341                 ShowMap(Utils->TreeRoot,user,0,matrix,totusers,totservers);
4342                 // Process each line one by one. The algorithm has a limit of
4343                 // 128 servers (which is far more than a spanning tree should have
4344                 // anyway, so we're ok). This limit can be raised simply by making
4345                 // the character matrix deeper, 128 rows taking 10k of memory.
4346                 for (int l = 1; l < line; l++)
4347                 {
4348                         // scan across the line looking for the start of the
4349                         // servername (the recursive part of the algorithm has placed
4350                         // the servers at indented positions depending on what they
4351                         // are related to)
4352                         int first_nonspace = 0;
4353                         while (matrix[l][first_nonspace] == ' ')
4354                         {
4355                                 first_nonspace++;
4356                         }
4357                         first_nonspace--;
4358                         // Draw the `- (corner) section: this may be overwritten by
4359                         // another L shape passing along the same vertical pane, becoming
4360                         // a |- (branch) section instead.
4361                         matrix[l][first_nonspace] = '-';
4362                         matrix[l][first_nonspace-1] = '`';
4363                         int l2 = l - 1;
4364                         // Draw upwards until we hit the parent server, causing possibly
4365                         // other corners (`-) to become branches (|-)
4366                         while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
4367                         {
4368                                 matrix[l2][first_nonspace-1] = '|';
4369                                 l2--;
4370                         }
4371                 }
4372                 // dump the whole lot to the user. This is the easy bit, honest.
4373                 for (int t = 0; t < line; t++)
4374                 {
4375                         user->WriteServ("006 %s :%s",user->nick,&matrix[t][0]);
4376                 }
4377                 float avg_users = totusers / totservers;
4378                 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);
4379         user->WriteServ("007 %s :End of /MAP",user->nick);
4380                 return;
4381         }
4382
4383         int HandleSquit(const char** parameters, int pcnt, userrec* user)
4384         {
4385                 TreeServer* s = Utils->FindServerMask(parameters[0]);
4386                 if (s)
4387                 {
4388                         if (s == Utils->TreeRoot)
4389                         {
4390                                  user->WriteServ("NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
4391                                 return 1;
4392                         }
4393                         TreeSocket* sock = s->GetSocket();
4394                         if (sock)
4395                         {
4396                                 ServerInstance->Log(DEBUG,"Splitting server %s",s->GetName().c_str());
4397                                 ServerInstance->SNO->WriteToSnoMask('l',"SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
4398                                 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
4399                                 ServerInstance->SE->DelFd(sock);
4400                                 sock->Close();
4401                                 delete sock;
4402                         }
4403                         else
4404                         {
4405                                 user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
4406                         }
4407                 }
4408                 else
4409                 {
4410                          user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
4411                 }
4412                 return 1;
4413         }
4414
4415         int HandleTime(const char** parameters, int pcnt, userrec* user)
4416         {
4417                 if ((IS_LOCAL(user)) && (pcnt))
4418                 {
4419                         TreeServer* found = Utils->FindServerMask(parameters[0]);
4420                         if (found)
4421                         {
4422                                 // we dont' override for local server
4423                                 if (found == Utils->TreeRoot)
4424                                         return 0;
4425                                 
4426                                 std::deque<std::string> params;
4427                                 params.push_back(found->GetName());
4428                                 params.push_back(user->nick);
4429                                 Utils->DoOneToOne(ServerInstance->Config->ServerName,"TIME",params,found->GetName());
4430                         }
4431                         else
4432                         {
4433                                 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
4434                         }
4435                 }
4436                 return 1;
4437         }
4438
4439         int HandleRemoteWhois(const char** parameters, int pcnt, userrec* user)
4440         {
4441                 if ((IS_LOCAL(user)) && (pcnt > 1))
4442                 {
4443                         userrec* remote = ServerInstance->FindNick(parameters[1]);
4444                         if ((remote) && (remote->GetFd() < 0))
4445                         {
4446                                 std::deque<std::string> params;
4447                                 params.push_back(parameters[1]);
4448                                 Utils->DoOneToOne(user->nick,"IDLE",params,remote->server);
4449                                 return 1;
4450                         }
4451                         else if (!remote)
4452                         {
4453                                 user->WriteServ("401 %s %s :No such nick/channel",user->nick, parameters[1]);
4454                                 user->WriteServ("318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
4455                                 return 1;
4456                         }
4457                 }
4458                 return 0;
4459         }
4460
4461         void DoPingChecks(time_t curtime)
4462         {
4463                 for (unsigned int j = 0; j < Utils->TreeRoot->ChildCount(); j++)
4464                 {
4465                         TreeServer* serv = Utils->TreeRoot->GetChild(j);
4466                         TreeSocket* sock = serv->GetSocket();
4467                         if (sock)
4468                         {
4469                                 if (curtime >= serv->NextPingTime())
4470                                 {
4471                                         if (serv->AnsweredLastPing())
4472                                         {
4473                                                 sock->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" PING "+serv->GetName());
4474                                                 serv->SetNextPingTime(curtime + 60);
4475                                         }
4476                                         else
4477                                         {
4478                                                 // they didnt answer, boot them
4479                                                 ServerInstance->SNO->WriteToSnoMask('l',"Server \002%s\002 pinged out",serv->GetName().c_str());
4480                                                 sock->Squit(serv,"Ping timeout");
4481                                                 ServerInstance->SE->DelFd(sock);
4482                                                 sock->Close();
4483                                                 delete sock;
4484                                                 return;
4485                                         }
4486                                 }
4487                         }
4488                 }
4489         }
4490
4491         void ConnectServer(Link* x)
4492         {
4493                 insp_inaddr binip;
4494
4495                 /* Do we already have an IP? If so, no need to resolve it. */
4496                 if (insp_aton(x->IPAddr.c_str(), &binip) > 0)
4497                 {
4498                         TreeSocket* newsocket = new TreeSocket(Utils, ServerInstance, x->IPAddr,x->Port,false,x->Timeout ? x->Timeout : 10,x->Name.c_str());
4499                         if (newsocket->GetFd() > -1)
4500                         {
4501                                 /* Handled automatically on success */
4502                         }
4503                         else
4504                         {
4505                                 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
4506                                 delete newsocket;
4507                                 Utils->DoFailOver(x);
4508                         }
4509                 }
4510                 else
4511                 {
4512                         try
4513                         {
4514                                 ServernameResolver* snr = new ServernameResolver((Module*)this, Utils, ServerInstance,x->IPAddr, *x);
4515                                 ServerInstance->AddResolver(snr);
4516                         }
4517                         catch (ModuleException& e)
4518                         {
4519                                 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
4520                                 Utils->DoFailOver(x);
4521                         }
4522                 }
4523         }
4524
4525         void AutoConnectServers(time_t curtime)
4526         {
4527                 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
4528                 {
4529                         if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
4530                         {
4531                                 ServerInstance->Log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
4532                                 x->NextConnectTime = curtime + x->AutoConnect;
4533                                 TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
4534                                 if (x->FailOver.length())
4535                                 {
4536                                         TreeServer* CheckFailOver = Utils->FindServer(x->FailOver.c_str());
4537                                         if (CheckFailOver)
4538                                         {
4539                                                 /* The failover for this server is currently a member of the network.
4540                                                  * The failover probably succeeded, where the main link did not.
4541                                                  * Don't try the main link until the failover is gone again.
4542                                                  */
4543                                                 continue;
4544                                         }
4545                                 }
4546                                 if (!CheckDupe)
4547                                 {
4548                                         // an autoconnected server is not connected. Check if its time to connect it
4549                                         ServerInstance->SNO->WriteToSnoMask('l',"AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
4550                                         this->ConnectServer(&(*x));
4551                                 }
4552                         }
4553                 }
4554         }
4555
4556         int HandleVersion(const char** parameters, int pcnt, userrec* user)
4557         {
4558                 // we've already checked if pcnt > 0, so this is safe
4559                 TreeServer* found = Utils->FindServerMask(parameters[0]);
4560                 if (found)
4561                 {
4562                         std::string Version = found->GetVersion();
4563                         user->WriteServ("351 %s :%s",user->nick,Version.c_str());
4564                         if (found == Utils->TreeRoot)
4565                         {
4566                                 std::stringstream out(ServerInstance->Config->data005);
4567                                 std::string token = "";
4568                                 std::string line5 = "";
4569                                 int token_counter = 0;
4570
4571                                 while (!out.eof())
4572                                 {
4573                                         out >> token;
4574                                         line5 = line5 + token + " ";   
4575                                         token_counter++;
4576
4577                                         if ((token_counter >= 13) || (out.eof() == true))
4578                                         {
4579                                                 user->WriteServ("005 %s %s:are supported by this server",user->nick,line5.c_str());
4580                                                 line5 = "";
4581                                                 token_counter = 0;
4582                                         }
4583                                 }
4584                         }
4585                 }
4586                 else
4587                 {
4588                         user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
4589                 }
4590                 return 1;
4591         }
4592         
4593         int HandleConnect(const char** parameters, int pcnt, userrec* user)
4594         {
4595                 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
4596                 {
4597                         if (ServerInstance->MatchText(x->Name.c_str(),parameters[0]))
4598                         {
4599                                 TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
4600                                 if (!CheckDupe)
4601                                 {
4602                                         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);
4603                                         ConnectServer(&(*x));
4604                                         return 1;
4605                                 }
4606                                 else
4607                                 {
4608                                         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());
4609                                         return 1;
4610                                 }
4611                         }
4612                 }
4613                 user->WriteServ("NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
4614                 return 1;
4615         }
4616
4617         void BroadcastTimeSync()
4618         {
4619                 std::deque<std::string> params;
4620                 params.push_back(ConvToStr(ServerInstance->Time(true)));
4621                 Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
4622         }
4623
4624         virtual int OnStats(char statschar, userrec* user, string_list &results)
4625         {
4626                 if (statschar == 'c')
4627                 {
4628                         for (unsigned int i = 0; i < Utils->LinkBlocks.size(); i++)
4629                         {
4630                                 results.push_back(std::string(ServerInstance->Config->ServerName)+" 213 "+user->nick+" C *@"+(Utils->LinkBlocks[i].HiddenFromStats ? "<hidden>" : Utils->LinkBlocks[i].IPAddr)+" * "+Utils->LinkBlocks[i].Name.c_str()+" "+ConvToStr(Utils->LinkBlocks[i].Port)+" "+(Utils->LinkBlocks[i].EncryptionKey != "" ? 'e' : '-')+(Utils->LinkBlocks[i].AutoConnect ? 'a' : '-')+'s');
4631                                 results.push_back(std::string(ServerInstance->Config->ServerName)+" 244 "+user->nick+" H * * "+Utils->LinkBlocks[i].Name.c_str());
4632                         }
4633                         results.push_back(std::string(ServerInstance->Config->ServerName)+" 219 "+user->nick+" "+statschar+" :End of /STATS report");
4634                         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);
4635                         return 1;
4636                 }
4637                 return 0;
4638         }
4639
4640         virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated, const std::string &original_line)
4641         {
4642                 /* If the command doesnt appear to be valid, we dont want to mess with it. */
4643                 if (!validated)
4644                         return 0;
4645
4646                 if (command == "CONNECT")
4647                 {
4648                         return this->HandleConnect(parameters,pcnt,user);
4649                 }
4650                 else if (command == "STATS")
4651                 {
4652                         return this->HandleStats(parameters,pcnt,user);
4653                 }
4654                 else if (command == "MOTD")
4655                 {
4656                         return this->HandleMotd(parameters,pcnt,user);
4657                 }
4658                 else if (command == "ADMIN")
4659                 {
4660                         return this->HandleAdmin(parameters,pcnt,user);
4661                 }
4662                 else if (command == "SQUIT")
4663                 {
4664                         return this->HandleSquit(parameters,pcnt,user);
4665                 }
4666                 else if (command == "MAP")
4667                 {
4668                         this->HandleMap(parameters,pcnt,user);
4669                         return 1;
4670                 }
4671                 else if ((command == "TIME") && (pcnt > 0))
4672                 {
4673                         return this->HandleTime(parameters,pcnt,user);
4674                 }
4675                 else if (command == "LUSERS")
4676                 {
4677                         this->HandleLusers(parameters,pcnt,user);
4678                         return 1;
4679                 }
4680                 else if (command == "LINKS")
4681                 {
4682                         this->HandleLinks(parameters,pcnt,user);
4683                         return 1;
4684                 }
4685                 else if (command == "WHOIS")
4686                 {
4687                         if (pcnt > 1)
4688                         {
4689                                 // remote whois
4690                                 return this->HandleRemoteWhois(parameters,pcnt,user);
4691                         }
4692                 }
4693                 else if ((command == "VERSION") && (pcnt > 0))
4694                 {
4695                         this->HandleVersion(parameters,pcnt,user);
4696                         return 1;
4697                 }
4698
4699                 return 0;
4700         }
4701
4702         virtual void OnPostCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, CmdResult result, const std::string &original_line)
4703         {
4704                 if ((result == CMD_SUCCESS) && (ServerInstance->IsValidModuleCommand(command, pcnt, user)))
4705                 {
4706                         // this bit of code cleverly routes all module commands
4707                         // to all remote severs *automatically* so that modules
4708                         // can just handle commands locally, without having
4709                         // to have any special provision in place for remote
4710                         // commands and linking protocols.
4711                         std::deque<std::string> params;
4712                         params.clear();
4713                         for (int j = 0; j < pcnt; j++)
4714                         {
4715                                 if (strchr(parameters[j],' '))
4716                                 {
4717                                         params.push_back(":" + std::string(parameters[j]));
4718                                 }
4719                                 else
4720                                 {
4721                                         params.push_back(std::string(parameters[j]));
4722                                 }
4723                         }
4724                         ServerInstance->Log(DEBUG,"Globally route '%s'",command.c_str());
4725                         Utils->DoOneToMany(user->nick,command,params);
4726                 }
4727         }
4728
4729         virtual void OnGetServerDescription(const std::string &servername,std::string &description)
4730         {
4731                 TreeServer* s = Utils->FindServer(servername);
4732                 if (s)
4733                 {
4734                         description = s->GetDesc();
4735                 }
4736         }
4737
4738         virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
4739         {
4740                 if (IS_LOCAL(source))
4741                 {
4742                         std::deque<std::string> params;
4743                         params.push_back(dest->nick);
4744                         params.push_back(channel->name);
4745                         Utils->DoOneToMany(source->nick,"INVITE",params);
4746                 }
4747         }
4748
4749         virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, const std::string &topic)
4750         {
4751                 std::deque<std::string> params;
4752                 params.push_back(chan->name);
4753                 params.push_back(":"+topic);
4754                 Utils->DoOneToMany(user->nick,"TOPIC",params);
4755         }
4756
4757         virtual void OnWallops(userrec* user, const std::string &text)
4758         {
4759                 if (IS_LOCAL(user))
4760                 {
4761                         std::deque<std::string> params;
4762                         params.push_back(":"+text);
4763                         Utils->DoOneToMany(user->nick,"WALLOPS",params);
4764                 }
4765         }
4766
4767         virtual void OnUserNotice(userrec* user, void* dest, int target_type, const std::string &text, char status)
4768         {
4769                 if (target_type == TYPE_USER)
4770                 {
4771                         userrec* d = (userrec*)dest;
4772                         if ((d->GetFd() < 0) && (IS_LOCAL(user)))
4773                         {
4774                                 std::deque<std::string> params;
4775                                 params.clear();
4776                                 params.push_back(d->nick);
4777                                 params.push_back(":"+text);
4778                                 Utils->DoOneToOne(user->nick,"NOTICE",params,d->server);
4779                         }
4780                 }
4781                 else if (target_type == TYPE_CHANNEL)
4782                 {
4783                         if (IS_LOCAL(user))
4784                         {
4785                                 chanrec *c = (chanrec*)dest;
4786                                 if (c)
4787                                 {
4788                                         std::string cname = c->name;
4789                                         if (status)
4790                                                 cname = status + cname;
4791                                         std::deque<TreeServer*> list;
4792                                         Utils->GetListOfServersForChannel(c,list);
4793                                         unsigned int ucount = list.size();
4794                                         for (unsigned int i = 0; i < ucount; i++)
4795                                         {
4796                                                 TreeSocket* Sock = list[i]->GetSocket();
4797                                                 if (Sock)
4798                                                         Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+cname+" :"+text);
4799                                         }
4800                                 }
4801                         }
4802                 }
4803                 else if (target_type == TYPE_SERVER)
4804                 {
4805                         if (IS_LOCAL(user))
4806                         {
4807                                 char* target = (char*)dest;
4808                                 std::deque<std::string> par;
4809                                 par.push_back(target);
4810                                 par.push_back(":"+text);
4811                                 Utils->DoOneToMany(user->nick,"NOTICE",par);
4812                         }
4813                 }
4814         }
4815
4816         virtual void OnUserMessage(userrec* user, void* dest, int target_type, const std::string &text, char status)
4817         {
4818                 if (target_type == TYPE_USER)
4819                 {
4820                         // route private messages which are targetted at clients only to the server
4821                         // which needs to receive them
4822                         userrec* d = (userrec*)dest;
4823                         if ((d->GetFd() < 0) && (IS_LOCAL(user)))
4824                         {
4825                                 std::deque<std::string> params;
4826                                 params.clear();
4827                                 params.push_back(d->nick);
4828                                 params.push_back(":"+text);
4829                                 Utils->DoOneToOne(user->nick,"PRIVMSG",params,d->server);
4830                         }
4831                 }
4832                 else if (target_type == TYPE_CHANNEL)
4833                 {
4834                         if (IS_LOCAL(user))
4835                         {
4836                                 chanrec *c = (chanrec*)dest;
4837                                 if (c)
4838                                 {
4839                                         std::string cname = c->name;
4840                                         if (status)
4841                                                 cname = status + cname;
4842                                         std::deque<TreeServer*> list;
4843                                         Utils->GetListOfServersForChannel(c,list);
4844                                         unsigned int ucount = list.size();
4845                                         for (unsigned int i = 0; i < ucount; i++)
4846                                         {
4847                                                 TreeSocket* Sock = list[i]->GetSocket();
4848                                                 if (Sock)
4849                                                         Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+cname+" :"+text);
4850                                         }
4851                                 }
4852                         }
4853                 }
4854                 else if (target_type == TYPE_SERVER)
4855                 {
4856                         if (IS_LOCAL(user))
4857                         {
4858                                 char* target = (char*)dest;
4859                                 std::deque<std::string> par;
4860                                 par.push_back(target);
4861                                 par.push_back(":"+text);
4862                                 Utils->DoOneToMany(user->nick,"PRIVMSG",par);
4863                         }
4864                 }
4865         }
4866
4867         virtual void OnBackgroundTimer(time_t curtime)
4868         {
4869                 AutoConnectServers(curtime);
4870                 DoPingChecks(curtime);
4871         }
4872
4873         virtual void OnUserJoin(userrec* user, chanrec* channel)
4874         {
4875                 // Only do this for local users
4876                 if (IS_LOCAL(user))
4877                 {
4878                         std::deque<std::string> params;
4879                         params.clear();
4880                         params.push_back(channel->name);
4881                         // set up their permissions and the channel TS with FJOIN.
4882                         // All users are FJOINed now, because a module may specify
4883                         // new joining permissions for the user.
4884                         params.clear();
4885                         params.push_back(channel->name);
4886                         params.push_back(ConvToStr(channel->age));
4887                         params.push_back(std::string(channel->GetAllPrefixChars(user))+","+std::string(user->nick));
4888                         Utils->DoOneToMany(ServerInstance->Config->ServerName,"FJOIN",params);
4889                         if (channel->GetUserCounter() == 1)
4890                         {
4891                                 /* First user in, sync the modes for the channel */
4892                                 params.pop_back();
4893                                 /* This is safe, all inspircd servers default to +nt */
4894                                 params.push_back("+nt");
4895                                 Utils->DoOneToMany(ServerInstance->Config->ServerName,"FMODE",params);
4896                         }
4897                 }
4898         }
4899
4900         virtual void OnChangeHost(userrec* user, const std::string &newhost)
4901         {
4902                 // only occurs for local clients
4903                 if (user->registered != REG_ALL)
4904                         return;
4905                 std::deque<std::string> params;
4906                 params.push_back(newhost);
4907                 Utils->DoOneToMany(user->nick,"FHOST",params);
4908         }
4909
4910         virtual void OnChangeName(userrec* user, const std::string &gecos)
4911         {
4912                 // only occurs for local clients
4913                 if (user->registered != REG_ALL)
4914                         return;
4915                 std::deque<std::string> params;
4916                 params.push_back(gecos);
4917                 Utils->DoOneToMany(user->nick,"FNAME",params);
4918         }
4919
4920         virtual void OnUserPart(userrec* user, chanrec* channel, const std::string &partmessage)
4921         {
4922                 if (IS_LOCAL(user))
4923                 {
4924                         std::deque<std::string> params;
4925                         params.push_back(channel->name);
4926                         if (partmessage != "")
4927                                 params.push_back(":"+partmessage);
4928                         Utils->DoOneToMany(user->nick,"PART",params);
4929                 }
4930         }
4931
4932         virtual void OnUserConnect(userrec* user)
4933         {
4934                 char agestr[MAXBUF];
4935                 if (IS_LOCAL(user))
4936                 {
4937                         std::deque<std::string> params;
4938                         snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
4939                         params.push_back(agestr);
4940                         params.push_back(user->nick);
4941                         params.push_back(user->host);
4942                         params.push_back(user->dhost);
4943                         params.push_back(user->ident);
4944                         params.push_back("+"+std::string(user->FormatModes()));
4945                         params.push_back(user->GetIPString());
4946                         params.push_back(":"+std::string(user->fullname));
4947                         Utils->DoOneToMany(ServerInstance->Config->ServerName,"NICK",params);
4948
4949                         // User is Local, change needs to be reflected!
4950                         TreeServer* SourceServer = Utils->FindServer(user->server);
4951                         if (SourceServer)
4952                         {
4953                                 SourceServer->AddUserCount();
4954                         }
4955
4956                 }
4957         }
4958
4959         virtual void OnUserQuit(userrec* user, const std::string &reason)
4960         {
4961                 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
4962                 {
4963                         std::deque<std::string> params;
4964                         params.push_back(":"+reason);
4965                         Utils->DoOneToMany(user->nick,"QUIT",params);
4966                 }
4967                 // Regardless, We need to modify the user Counts..
4968                 TreeServer* SourceServer = Utils->FindServer(user->server);
4969                 if (SourceServer)
4970                 {
4971                         SourceServer->DelUserCount();
4972                 }
4973
4974         }
4975
4976         virtual void OnUserPostNick(userrec* user, const std::string &oldnick)
4977         {
4978                 if (IS_LOCAL(user))
4979                 {
4980                         std::deque<std::string> params;
4981                         params.push_back(user->nick);
4982                         Utils->DoOneToMany(oldnick,"NICK",params);
4983                 }
4984         }
4985
4986         virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, const std::string &reason)
4987         {
4988                 if ((source) && (IS_LOCAL(source)))
4989                 {
4990                         std::deque<std::string> params;
4991                         params.push_back(chan->name);
4992                         params.push_back(user->nick);
4993                         params.push_back(":"+reason);
4994                         Utils->DoOneToMany(source->nick,"KICK",params);
4995                 }
4996                 else if (!source)
4997                 {
4998                         std::deque<std::string> params;
4999                         params.push_back(chan->name);
5000                         params.push_back(user->nick);
5001                         params.push_back(":"+reason);
5002                         Utils->DoOneToMany(ServerInstance->Config->ServerName,"KICK",params);
5003                 }
5004         }
5005
5006         virtual void OnRemoteKill(userrec* source, userrec* dest, const std::string &reason)
5007         {
5008                 std::deque<std::string> params;
5009                 params.push_back(dest->nick);
5010                 params.push_back(":"+reason);
5011                 Utils->DoOneToMany(source->nick,"KILL",params);
5012         }
5013
5014         virtual void OnRehash(const std::string &parameter)
5015         {
5016                 if (parameter != "")
5017                 {
5018                         std::deque<std::string> params;
5019                         params.push_back(parameter);
5020                         Utils->DoOneToMany(ServerInstance->Config->ServerName,"REHASH",params);
5021                         // check for self
5022                         if (ServerInstance->MatchText(ServerInstance->Config->ServerName,parameter))
5023                         {
5024                                 ServerInstance->WriteOpers("*** Remote rehash initiated from server \002%s\002",ServerInstance->Config->ServerName);
5025                                 ServerInstance->RehashServer();
5026                         }
5027                 }
5028                 Utils->ReadConfiguration(false);
5029         }
5030
5031         // note: the protocol does not allow direct umode +o except
5032         // via NICK with 8 params. sending OPERTYPE infers +o modechange
5033         // locally.
5034         virtual void OnOper(userrec* user, const std::string &opertype)
5035         {
5036                 if (IS_LOCAL(user))
5037                 {
5038                         std::deque<std::string> params;
5039                         params.push_back(opertype);
5040                         Utils->DoOneToMany(user->nick,"OPERTYPE",params);
5041                 }
5042         }
5043
5044         void OnLine(userrec* source, const std::string &host, bool adding, char linetype, long duration, const std::string &reason)
5045         {
5046                 if (!source)
5047                 {
5048                         /* Server-set lines */
5049                         char data[MAXBUF];
5050                         snprintf(data,MAXBUF,"%c %s %s %lu %lu :%s", linetype, host.c_str(), ServerInstance->Config->ServerName, (unsigned long)ServerInstance->Time(false),
5051                                         (unsigned long)duration, reason.c_str());
5052                         std::deque<std::string> params;
5053                         params.push_back(data);
5054                         Utils->DoOneToMany(ServerInstance->Config->ServerName, "ADDLINE", params);
5055                 }
5056                 else
5057                 {
5058                         if (IS_LOCAL(source))
5059                         {
5060                                 char type[8];
5061                                 snprintf(type,8,"%cLINE",linetype);
5062                                 std::string stype = type;
5063                                 if (adding)
5064                                 {
5065                                         char sduration[MAXBUF];
5066                                         snprintf(sduration,MAXBUF,"%ld",duration);
5067                                         std::deque<std::string> params;
5068                                         params.push_back(host);
5069                                         params.push_back(sduration);
5070                                         params.push_back(":"+reason);
5071                                         Utils->DoOneToMany(source->nick,stype,params);
5072                                 }
5073                                 else
5074                                 {
5075                                         std::deque<std::string> params;
5076                                         params.push_back(host);
5077                                         Utils->DoOneToMany(source->nick,stype,params);
5078                                 }
5079                         }
5080                 }
5081         }
5082
5083         virtual void OnAddGLine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
5084         {
5085                 OnLine(source,hostmask,true,'G',duration,reason);
5086         }
5087         
5088         virtual void OnAddZLine(long duration, userrec* source, const std::string &reason, const std::string &ipmask)
5089         {
5090                 OnLine(source,ipmask,true,'Z',duration,reason);
5091         }
5092
5093         virtual void OnAddQLine(long duration, userrec* source, const std::string &reason, const std::string &nickmask)
5094         {
5095                 OnLine(source,nickmask,true,'Q',duration,reason);
5096         }
5097
5098         virtual void OnAddELine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
5099         {
5100                 OnLine(source,hostmask,true,'E',duration,reason);
5101         }
5102
5103         virtual void OnDelGLine(userrec* source, const std::string &hostmask)
5104         {
5105                 OnLine(source,hostmask,false,'G',0,"");
5106         }
5107
5108         virtual void OnDelZLine(userrec* source, const std::string &ipmask)
5109         {
5110                 OnLine(source,ipmask,false,'Z',0,"");
5111         }
5112
5113         virtual void OnDelQLine(userrec* source, const std::string &nickmask)
5114         {
5115                 OnLine(source,nickmask,false,'Q',0,"");
5116         }
5117
5118         virtual void OnDelELine(userrec* source, const std::string &hostmask)
5119         {
5120                 OnLine(source,hostmask,false,'E',0,"");
5121         }
5122
5123         virtual void OnMode(userrec* user, void* dest, int target_type, const std::string &text)
5124         {
5125                 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
5126                 {
5127                         if (target_type == TYPE_USER)
5128                         {
5129                                 userrec* u = (userrec*)dest;
5130                                 std::deque<std::string> params;
5131                                 params.push_back(u->nick);
5132                                 params.push_back(text);
5133                                 Utils->DoOneToMany(user->nick,"MODE",params);
5134                         }
5135                         else
5136                         {
5137                                 chanrec* c = (chanrec*)dest;
5138                                 std::deque<std::string> params;
5139                                 params.push_back(c->name);
5140                                 params.push_back(text);
5141                                 Utils->DoOneToMany(user->nick,"MODE",params);
5142                         }
5143                 }
5144         }
5145
5146         virtual void OnSetAway(userrec* user)
5147         {
5148                 if (IS_LOCAL(user))
5149                 {
5150                         std::deque<std::string> params;
5151                         params.push_back(":"+std::string(user->awaymsg));
5152                         Utils->DoOneToMany(user->nick,"AWAY",params);
5153                 }
5154         }
5155
5156         virtual void OnCancelAway(userrec* user)
5157         {
5158                 if (IS_LOCAL(user))
5159                 {
5160                         std::deque<std::string> params;
5161                         params.clear();
5162                         Utils->DoOneToMany(user->nick,"AWAY",params);
5163                 }
5164         }
5165
5166         virtual void ProtoSendMode(void* opaque, int target_type, void* target, const std::string &modeline)
5167         {
5168                 TreeSocket* s = (TreeSocket*)opaque;
5169                 if (target)
5170                 {
5171                         if (target_type == TYPE_USER)
5172                         {
5173                                 userrec* u = (userrec*)target;
5174                                 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+u->nick+" "+ConvToStr(u->age)+" "+modeline);
5175                         }
5176                         else
5177                         {
5178                                 chanrec* c = (chanrec*)target;
5179                                 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age)+" "+modeline);
5180                         }
5181                 }
5182         }
5183
5184         virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, const std::string &extname, const std::string &extdata)
5185         {
5186                 TreeSocket* s = (TreeSocket*)opaque;
5187                 if (target)
5188                 {
5189                         if (target_type == TYPE_USER)
5190                         {
5191                                 userrec* u = (userrec*)target;
5192                                 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+u->nick+" "+extname+" :"+extdata);
5193                         }
5194                         else if (target_type == TYPE_OTHER)
5195                         {
5196                                 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA * "+extname+" :"+extdata);
5197                         }
5198                         else if (target_type == TYPE_CHANNEL)
5199                         {
5200                                 chanrec* c = (chanrec*)target;
5201                                 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+c->name+" "+extname+" :"+extdata);
5202                         }
5203                 }
5204         }
5205
5206         virtual void OnEvent(Event* event)
5207         {
5208                 std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
5209
5210                 if (event->GetEventID() == "send_metadata")
5211                 {
5212                         if (params->size() < 3)
5213                                 return;
5214                         (*params)[2] = ":" + (*params)[2];
5215                         Utils->DoOneToMany(ServerInstance->Config->ServerName,"METADATA",*params);
5216                 }
5217                 else if (event->GetEventID() == "send_topic")
5218                 {
5219                         if (params->size() < 2)
5220                                 return;
5221                         (*params)[1] = ":" + (*params)[1];
5222                         params->insert(params->begin() + 1,ServerInstance->Config->ServerName);
5223                         params->insert(params->begin() + 1,ConvToStr(ServerInstance->Time(true)));
5224                         Utils->DoOneToMany(ServerInstance->Config->ServerName,"FTOPIC",*params);
5225                 }
5226                 else if (event->GetEventID() == "send_mode")
5227                 {
5228                         if (params->size() < 2)
5229                                 return;
5230                         // Insert the TS value of the object, either userrec or chanrec
5231                         time_t ourTS = 0;
5232                         userrec* a = ServerInstance->FindNick((*params)[0]);
5233                         if (a)
5234                         {
5235                                 ourTS = a->age;
5236                         }
5237                         else
5238                         {
5239                                 chanrec* a = ServerInstance->FindChan((*params)[0]);
5240                                 if (a)
5241                                 {
5242                                         ourTS = a->age;
5243                                 }
5244                         }
5245                         params->insert(params->begin() + 1,ConvToStr(ourTS));
5246                         Utils->DoOneToMany(ServerInstance->Config->ServerName,"FMODE",*params);
5247                 }
5248                 else if (event->GetEventID() == "send_mode_explicit")
5249                 {
5250                         if (params->size() < 2)
5251                                 return;
5252                         Utils->DoOneToMany(ServerInstance->Config->ServerName,"MODE",*params);
5253                 }
5254                 else if (event->GetEventID() == "send_opers")
5255                 {
5256                         if (params->size() < 1)
5257                                 return;
5258                         (*params)[0] = ":" + (*params)[0];
5259                         Utils->DoOneToMany(ServerInstance->Config->ServerName,"OPERNOTICE",*params);
5260                 }
5261                 else if (event->GetEventID() == "send_modeset")
5262                 {
5263                         if (params->size() < 2)
5264                                 return;
5265                         (*params)[1] = ":" + (*params)[1];
5266                         Utils->DoOneToMany(ServerInstance->Config->ServerName,"MODENOTICE",*params);
5267                 }
5268                 else if (event->GetEventID() == "send_snoset")
5269                 {
5270                         if (params->size() < 2)
5271                                 return;
5272                         (*params)[1] = ":" + (*params)[1];
5273                         Utils->DoOneToMany(ServerInstance->Config->ServerName,"SNONOTICE",*params);
5274                 }
5275                 else if (event->GetEventID() == "send_push")
5276                 {
5277                         if (params->size() < 2)
5278                                 return;
5279                         
5280                         userrec *a = ServerInstance->FindNick((*params)[0]);
5281                         
5282                         if (!a)
5283                                 return;
5284                         
5285                         (*params)[1] = ":" + (*params)[1];
5286                         Utils->DoOneToOne(ServerInstance->Config->ServerName, "PUSH", *params, a->server);
5287                 }
5288         }
5289
5290         virtual ~ModuleSpanningTree()
5291         {
5292                 ServerInstance->Log(DEBUG,"Performing unload of spanningtree!");
5293                 /* This will also free the listeners */
5294                 delete Utils;
5295                 if (SyncTimer)
5296                         ServerInstance->Timers->DelTimer(SyncTimer);
5297         }
5298
5299         virtual Version GetVersion()
5300         {
5301                 return Version(1,1,0,2,VF_VENDOR,API_VERSION);
5302         }
5303
5304         void Implements(char* List)
5305         {
5306                 List[I_OnPreCommand] = List[I_OnGetServerDescription] = List[I_OnUserInvite] = List[I_OnPostLocalTopicChange] = 1;
5307                 List[I_OnWallops] = List[I_OnUserNotice] = List[I_OnUserMessage] = List[I_OnBackgroundTimer] = 1;
5308                 List[I_OnUserJoin] = List[I_OnChangeHost] = List[I_OnChangeName] = List[I_OnUserPart] = List[I_OnUserConnect] = 1;
5309                 List[I_OnUserQuit] = List[I_OnUserPostNick] = List[I_OnUserKick] = List[I_OnRemoteKill] = List[I_OnRehash] = 1;
5310                 List[I_OnOper] = List[I_OnAddGLine] = List[I_OnAddZLine] = List[I_OnAddQLine] = List[I_OnAddELine] = 1;
5311                 List[I_OnDelGLine] = List[I_OnDelZLine] = List[I_OnDelQLine] = List[I_OnDelELine] = List[I_ProtoSendMode] = List[I_OnMode] = 1;
5312                 List[I_OnStats] = List[I_ProtoSendMetaData] = List[I_OnEvent] = List[I_OnSetAway] = List[I_OnCancelAway] = List[I_OnPostCommand] = 1;
5313         }
5314
5315         /* It is IMPORTANT that m_spanningtree is the last module in the chain
5316          * so that any activity it sees is FINAL, e.g. we arent going to send out
5317          * a NICK message before m_cloaking has finished putting the +x on the user,
5318          * etc etc.
5319          * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
5320          * the module call queue.
5321          */
5322         Priority Prioritize()
5323         {
5324                 return PRIORITY_LAST;
5325         }
5326 };
5327
5328 TimeSyncTimer::TimeSyncTimer(InspIRCd *Inst, ModuleSpanningTree *Mod) : InspTimer(43200, Inst->Time()), Instance(Inst), Module(Mod)
5329 {
5330 }
5331
5332 void TimeSyncTimer::Tick(time_t TIME)
5333 {
5334         Module->BroadcastTimeSync();
5335         Module->SyncTimer = new TimeSyncTimer(Instance, Module);
5336         Instance->Timers->AddTimer(Module->SyncTimer);
5337 }
5338
5339 void SpanningTreeUtilities::DoFailOver(Link* x)
5340 {
5341         if (x->FailOver.length())
5342         {
5343                 if (x->FailOver == x->Name)
5344                 {
5345                         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());
5346                         return;
5347                 }
5348                 Link* TryThisOne = this->FindLink(x->FailOver.c_str());
5349                 if (TryThisOne)
5350                 {
5351                         ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Trying failover link for \002%s\002: \002%s\002...", x->Name.c_str(), TryThisOne->Name.c_str());
5352                         Creator->ConnectServer(TryThisOne);
5353                 }
5354                 else
5355                 {
5356                         ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Invalid failover server specified for server \002%s\002, will not follow!", x->Name.c_str());
5357                 }
5358         }
5359 }
5360
5361 Link* SpanningTreeUtilities::FindLink(const std::string& name)
5362 {
5363         for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
5364         {
5365                 if (ServerInstance->MatchText(x->Name.c_str(), name.c_str()))
5366                 {
5367                         return &(*x);
5368                 }
5369         }
5370         return NULL;
5371 }
5372
5373 class ModuleSpanningTreeFactory : public ModuleFactory
5374 {
5375  public:
5376         ModuleSpanningTreeFactory()
5377         {
5378         }
5379         
5380         ~ModuleSpanningTreeFactory()
5381         {
5382         }
5383         
5384         virtual Module * CreateModule(InspIRCd* Me)
5385         {
5386                 return new ModuleSpanningTree(Me);
5387         }
5388         
5389 };
5390
5391
5392 extern "C" void * init_module( void )
5393 {
5394         return new ModuleSpanningTreeFactory;
5395 }