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