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