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