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