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