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