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