]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree.cpp
JOIN now has a TS parameter on it. The client protocol will ignore this when we pass...
[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                                         ServerInstance->Log(SPARSE,"Warning! Invalid user %s in FJOIN to channel %s IGNORED", who->nick, channel.c_str());
1640                                         continue;
1641                                 }
1642                         }
1643                 }
1644                 /* there werent enough modes built up to flush it during FJOIN,
1645                  * or, there are a number left over. flush them out.
1646                  */
1647                 if ((modectr > 2) && (who) && (us))
1648                 {
1649                         if (ourTS >= TS)
1650                         {
1651                                 ServerInstance->Log(DEBUG,"Our our channel newer than theirs, accepting their modes");
1652                                 this->Instance->SendMode((const char**)mode_users,modectr,who);
1653                                 if (ourTS != TS)
1654                                 {
1655                                         ServerInstance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",us->name,ourTS,TS);
1656                                         us->age = TS;
1657                                         ourTS = TS;
1658                                 }
1659                         }
1660                         else
1661                         {
1662                                 ServerInstance->Log(DEBUG,"Their channel newer than ours, bouncing their modes");
1663                                 std::deque<std::string> params;
1664                                 *mode_users[1] = '-';
1665                                 for (unsigned int x = 0; x < modectr; x++)
1666                                 {
1667                                         if (x == 1)
1668                                         {
1669                                                 params.push_back(ConvToStr(us->age));
1670                                         }
1671                                         params.push_back(mode_users[x]);
1672                                 }
1673                                 DoOneToMany(this->Instance->Config->ServerName,"FMODE",params);
1674                         }
1675
1676                         for (unsigned int f = 2; f < modectr; f++)
1677                                 free(mode_users[f]);
1678                 }
1679                 return true;
1680         }
1681
1682         /* NICK command */
1683         bool IntroduceClient(std::string source, std::deque<std::string> &params)
1684         {
1685                 if (params.size() < 8)
1686                         return true;
1687                 if (params.size() > 8)
1688                 {
1689                         this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[1]+"?)");
1690                         return true;
1691                 }
1692                 // NICK age nick host dhost ident +modes ip :gecos
1693                 //       0    1   2     3     4      5   6     7
1694                 time_t age = atoi(params[0].c_str());
1695                 
1696                 /* This used to have a pretty craq'y loop doing the same thing,
1697                  * now we just let the STL do the hard work (more efficiently)
1698                  */
1699                 std::string::size_type pos_after_plus = params[5].find_first_not_of('+');
1700                 if (pos_after_plus != std::string::npos)
1701                         params[5] = params[5].substr(pos_after_plus);
1702                 
1703                 const char* tempnick = params[1].c_str();
1704                 ServerInstance->Log(DEBUG,"Introduce client %s!%s@%s",tempnick,params[4].c_str(),params[2].c_str());
1705                 
1706                 user_hash::iterator iter = this->Instance->clientlist.find(tempnick);
1707                 
1708                 if (iter != this->Instance->clientlist.end())
1709                 {
1710                         // nick collision
1711                         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);
1712                         this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+tempnick+" :Nickname collision");
1713                         return true;
1714                 }
1715
1716                 userrec* _new = new userrec(this->Instance);
1717                 this->Instance->clientlist[tempnick] = _new;
1718                 _new->SetFd(FD_MAGIC_NUMBER);
1719                 strlcpy(_new->nick, tempnick,NICKMAX-1);
1720                 strlcpy(_new->host, params[2].c_str(),63);
1721                 strlcpy(_new->dhost, params[3].c_str(),63);
1722                 _new->server = this->Instance->FindServerNamePtr(source.c_str());
1723                 strlcpy(_new->ident, params[4].c_str(),IDENTMAX);
1724                 strlcpy(_new->fullname, params[7].c_str(),MAXGECOS);
1725                 _new->registered = REG_ALL;
1726                 _new->signon = age;
1727                 
1728                 for (std::string::iterator v = params[5].begin(); v != params[5].end(); v++)
1729                         _new->modes[(*v)-65] = 1;
1730
1731 #ifdef SUPPORT_IP6LINKS
1732                 if (params[6].find_first_of(":") != std::string::npos)
1733                         _new->SetSockAddr(AF_INET6, params[6].c_str(), 0);
1734                 else
1735 #endif
1736                         _new->SetSockAddr(AF_INET, params[6].c_str(), 0);
1737
1738                 this->Instance->SNO->WriteToSnoMask('C',"Client connecting at %s: %s!%s@%s [%s]",_new->server,_new->nick,_new->ident,_new->host, _new->GetIPString());
1739
1740                 params[7] = ":" + params[7];
1741                 DoOneToAllButSender(source,"NICK",params,source);
1742
1743                 // Increment the Source Servers User Count..
1744                 TreeServer* SourceServer = FindServer(source);
1745                 if (SourceServer)
1746                 {
1747                         ServerInstance->Log(DEBUG,"Found source server of %s",_new->nick);
1748                         SourceServer->AddUserCount();
1749                 }
1750
1751                 return true;
1752         }
1753
1754         /* Send one or more FJOINs for a channel of users.
1755          * If the length of a single line is more than 480-NICKMAX
1756          * in length, it is split over multiple lines.
1757          */
1758         void SendFJoins(TreeServer* Current, chanrec* c)
1759         {
1760                 ServerInstance->Log(DEBUG,"Sending FJOINs to other server for %s",c->name);
1761                 char list[MAXBUF];
1762                 std::string individual_halfops = std::string(":")+this->Instance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age);
1763                 
1764                 size_t dlen, curlen;
1765                 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1766                 int numusers = 0;
1767                 char* ptr = list + dlen;
1768
1769                 CUList *ulist = c->GetUsers();
1770                 std::vector<userrec*> specific_halfop;
1771                 std::vector<userrec*> specific_voice;
1772                 std::string modes = "";
1773                 std::string params = "";
1774
1775                 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1776                 {
1777                         // The first parameter gets a : before it
1778                         size_t ptrlen = snprintf(ptr, MAXBUF, " %s%s,%s", !numusers ? ":" : "", c->GetAllPrefixChars(i->second), i->second->nick);
1779
1780                         curlen += ptrlen;
1781                         ptr += ptrlen;
1782
1783                         numusers++;
1784
1785                         if (curlen > (480-NICKMAX))
1786                         {
1787                                 this->WriteLine(list);
1788                                 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1789                                 ptr = list + dlen;
1790                                 ptrlen = 0;
1791                                 numusers = 0;
1792                         }
1793                 }
1794
1795                 if (numusers)
1796                         this->WriteLine(list);
1797
1798                 for (BanList::iterator b = c->bans.begin(); b != c->bans.end(); b++)
1799                 {
1800                         modes.append("b");
1801                         params.append(b->data).append(" ");
1802                 }
1803                 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age)+" +"+c->ChanModes(true)+modes+" "+params);
1804         }
1805
1806         /* Send G, Q, Z and E lines */
1807         void SendXLines(TreeServer* Current)
1808         {
1809                 char data[MAXBUF];
1810                 std::string n = this->Instance->Config->ServerName;
1811                 const char* sn = n.c_str();
1812                 int iterations = 0;
1813                 /* Yes, these arent too nice looking, but they get the job done */
1814                 for (std::vector<ZLine>::iterator i = Instance->XLines->zlines.begin(); i != Instance->XLines->zlines.end(); i++, iterations++)
1815                 {
1816                         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);
1817                         this->WriteLine(data);
1818                 }
1819                 for (std::vector<QLine>::iterator i = Instance->XLines->qlines.begin(); i != Instance->XLines->qlines.end(); i++, iterations++)
1820                 {
1821                         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);
1822                         this->WriteLine(data);
1823                 }
1824                 for (std::vector<GLine>::iterator i = Instance->XLines->glines.begin(); i != Instance->XLines->glines.end(); i++, iterations++)
1825                 {
1826                         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);
1827                         this->WriteLine(data);
1828                 }
1829                 for (std::vector<ELine>::iterator i = Instance->XLines->elines.begin(); i != Instance->XLines->elines.end(); i++, iterations++)
1830                 {
1831                         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);
1832                         this->WriteLine(data);
1833                 }
1834                 for (std::vector<ZLine>::iterator i = Instance->XLines->pzlines.begin(); i != Instance->XLines->pzlines.end(); i++, iterations++)
1835                 {
1836                         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);
1837                         this->WriteLine(data);
1838                 }
1839                 for (std::vector<QLine>::iterator i = Instance->XLines->pqlines.begin(); i != Instance->XLines->pqlines.end(); i++, iterations++)
1840                 {
1841                         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);
1842                         this->WriteLine(data);
1843                 }
1844                 for (std::vector<GLine>::iterator i = Instance->XLines->pglines.begin(); i != Instance->XLines->pglines.end(); i++, iterations++)
1845                 {
1846                         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);
1847                         this->WriteLine(data);
1848                 }
1849                 for (std::vector<ELine>::iterator i = Instance->XLines->pelines.begin(); i != Instance->XLines->pelines.end(); i++, iterations++)
1850                 {
1851                         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);
1852                         this->WriteLine(data);
1853                 }
1854         }
1855
1856         /* Send channel modes and topics */
1857         void SendChannelModes(TreeServer* Current)
1858         {
1859                 char data[MAXBUF];
1860                 std::deque<std::string> list;
1861                 int iterations = 0;
1862                 std::string n = this->Instance->Config->ServerName;
1863                 const char* sn = n.c_str();
1864                 for (chan_hash::iterator c = this->Instance->chanlist.begin(); c != this->Instance->chanlist.end(); c++, iterations++)
1865                 {
1866                         SendFJoins(Current, c->second);
1867                         if (*c->second->topic)
1868                         {
1869                                 snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",sn,c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
1870                                 this->WriteLine(data);
1871                         }
1872                         FOREACH_MOD_I(this->Instance,I_OnSyncChannel,OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this));
1873                         list.clear();
1874                         c->second->GetExtList(list);
1875                         for (unsigned int j = 0; j < list.size(); j++)
1876                         {
1877                                 FOREACH_MOD_I(this->Instance,I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
1878                         }
1879                 }
1880         }
1881
1882         /* send all users and their oper state/modes */
1883         void SendUsers(TreeServer* Current)
1884         {
1885                 char data[MAXBUF];
1886                 std::deque<std::string> list;
1887                 int iterations = 0;
1888                 for (user_hash::iterator u = this->Instance->clientlist.begin(); u != this->Instance->clientlist.end(); u++, iterations++)
1889                 {
1890                         if (u->second->registered == REG_ALL)
1891                         {
1892                                 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);
1893                                 this->WriteLine(data);
1894                                 if (*u->second->oper)
1895                                 {
1896                                         this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
1897                                 }
1898                                 if (*u->second->awaymsg)
1899                                 {
1900                                         this->WriteLine(":"+std::string(u->second->nick)+" AWAY :"+std::string(u->second->awaymsg));
1901                                 }
1902                                 FOREACH_MOD_I(this->Instance,I_OnSyncUser,OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this));
1903                                 list.clear();
1904                                 u->second->GetExtList(list);
1905                                 for (unsigned int j = 0; j < list.size(); j++)
1906                                 {
1907                                         FOREACH_MOD_I(this->Instance,I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
1908                                 }
1909                         }
1910                 }
1911         }
1912
1913         /* This function is called when we want to send a netburst to a local
1914          * server. There is a set order we must do this, because for example
1915          * users require their servers to exist, and channels require their
1916          * users to exist. You get the idea.
1917          */
1918         void DoBurst(TreeServer* s)
1919         {
1920                 std::string burst = "BURST "+ConvToStr(time(NULL));
1921                 std::string endburst = "ENDBURST";
1922                 // Because by the end of the netburst, it  could be gone!
1923                 std::string name = s->GetName();
1924                 this->Instance->SNO->WriteToSnoMask('l',"Bursting to \2"+name+"\2.");
1925                 this->WriteLine(burst);
1926                 /* send our version string */
1927                 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" VERSION :"+this->Instance->GetVersionString());
1928                 /* Send server tree */
1929                 this->SendServers(TreeRoot,s,1);
1930                 /* Send users and their oper status */
1931                 this->SendUsers(s);
1932                 /* Send everything else (channel modes, xlines etc) */
1933                 this->SendChannelModes(s);
1934                 this->SendXLines(s);            
1935                 FOREACH_MOD_I(this->Instance,I_OnSyncOtherMetaData,OnSyncOtherMetaData((Module*)TreeProtocolModule,(void*)this));
1936                 this->WriteLine(endburst);
1937                 this->Instance->SNO->WriteToSnoMask('l',"Finished bursting to \2"+name+"\2.");
1938         }
1939
1940         /* This function is called when we receive data from a remote
1941          * server. We buffer the data in a std::string (it doesnt stay
1942          * there for long), reading using InspSocket::Read() which can
1943          * read up to 16 kilobytes in one operation.
1944          *
1945          * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
1946          * THE SOCKET OBJECT FOR US.
1947          */
1948         virtual bool OnDataReady()
1949         {
1950                 char* data = this->Read();
1951                 /* Check that the data read is a valid pointer and it has some content */
1952                 if (data && *data)
1953                 {
1954                         this->in_buffer.append(data);
1955                         /* While there is at least one new line in the buffer,
1956                          * do something useful (we hope!) with it.
1957                          */
1958                         while (in_buffer.find("\n") != std::string::npos)
1959                         {
1960                                 std::string ret = in_buffer.substr(0,in_buffer.find("\n")-1);
1961                                 in_buffer = in_buffer.substr(in_buffer.find("\n")+1,in_buffer.length()-in_buffer.find("\n"));
1962                                 if (ret.find("\r") != std::string::npos)
1963                                         ret = in_buffer.substr(0,in_buffer.find("\r")-1);
1964                                 /* Process this one, abort if it
1965                                  * didnt return true.
1966                                  */
1967                                 if (this->ctx_in)
1968                                 {
1969                                         char out[1024];
1970                                         char result[1024];
1971                                         memset(result,0,1024);
1972                                         memset(out,0,1024);
1973                                         ServerInstance->Log(DEBUG,"Original string '%s'",ret.c_str());
1974                                         /* ERROR + CAPAB is still allowed unencryped */
1975                                         if ((ret.substr(0,7) != "ERROR :") && (ret.substr(0,6) != "CAPAB "))
1976                                         {
1977                                                 int nbytes = from64tobits(out, ret.c_str(), 1024);
1978                                                 if ((nbytes > 0) && (nbytes < 1024))
1979                                                 {
1980                                                         ServerInstance->Log(DEBUG,"m_spanningtree: decrypt %d bytes",nbytes);
1981                                                         ctx_in->Decrypt(out, result, nbytes, 0);
1982                                                         for (int t = 0; t < nbytes; t++)
1983                                                                 if (result[t] == '\7') result[t] = 0;
1984                                                         ret = result;
1985                                                 }
1986                                         }
1987                                 }
1988                                 if (!this->ProcessLine(ret))
1989                                 {
1990                                         ServerInstance->Log(DEBUG,"ProcessLine says no!");
1991                                         return false;
1992                                 }
1993                         }
1994                         return true;
1995                 }
1996                 /* EAGAIN returns an empty but non-NULL string, so this
1997                  * evaluates to TRUE for EAGAIN but to FALSE for EOF.
1998                  */
1999                 return (data && !*data);
2000         }
2001
2002         int WriteLine(std::string line)
2003         {
2004                 ServerInstance->Log(DEBUG,"OUT: %s",line.c_str());
2005                 if (this->ctx_out)
2006                 {
2007                         char result[10240];
2008                         char result64[10240];
2009                         if (this->keylength)
2010                         {
2011                                 // pad it to the key length
2012                                 int n = this->keylength - (line.length() % this->keylength);
2013                                 if (n)
2014                                 {
2015                                         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);
2016                                         line.append(n,'\7');
2017                                 }
2018                         }
2019                         unsigned int ll = line.length();
2020                         ctx_out->Encrypt(line.c_str(), result, ll, 0);
2021                         to64frombits((unsigned char*)result64,(unsigned char*)result,ll);
2022                         line = result64;
2023                         //int from64tobits(char *out, const char *in, int maxlen);
2024                 }
2025                 return this->Write(line + "\r\n");
2026         }
2027
2028         /* Handle ERROR command */
2029         bool Error(std::deque<std::string> &params)
2030         {
2031                 if (params.size() < 1)
2032                         return false;
2033                 this->Instance->SNO->WriteToSnoMask('l',"ERROR from %s: %s",(InboundServerName != "" ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
2034                 /* we will return false to cause the socket to close. */
2035                 return false;
2036         }
2037
2038         /* remote MOTD. leet, huh? */
2039         bool Motd(std::string prefix, std::deque<std::string> &params)
2040         {
2041                 if (params.size() > 0)
2042                 {
2043                         if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
2044                         {
2045                                 /* It's for our server */
2046                                 string_list results;
2047                                 userrec* source = this->Instance->FindNick(prefix);
2048
2049                                 if (source)
2050                                 {
2051                                         std::deque<std::string> par;
2052                                         par.push_back(prefix);
2053                                         par.push_back("");
2054
2055                                         if (!ServerInstance->Config->MOTD.size())
2056                                         {
2057                                                 par[1] = std::string("::")+ServerInstance->Config->ServerName+" 422 "+source->nick+" :Message of the day file is missing.";
2058                                                 DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2059                                                 return true;
2060                                         }
2061    
2062                                         par[1] = std::string("::")+ServerInstance->Config->ServerName+" 375 "+source->nick+" :"+ServerInstance->Config->ServerName+" message of the day";
2063                                         DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2064    
2065                                         for (unsigned int i = 0; i < ServerInstance->Config->MOTD.size(); i++)
2066                                         {
2067                                                 par[1] = std::string("::")+ServerInstance->Config->ServerName+" 372 "+source->nick+" :- "+ServerInstance->Config->MOTD[i];
2068                                                 DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2069                                         }
2070      
2071                                         par[1] = std::string("::")+ServerInstance->Config->ServerName+" 376 "+source->nick+" End of message of the day.";
2072                                         DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2073                                 }
2074                         }
2075                         else
2076                         {
2077                                 /* Pass it on */
2078                                 userrec* source = this->Instance->FindNick(prefix);
2079                                 if (source)
2080                                         DoOneToOne(prefix, "MOTD", params, params[0]);
2081                         }
2082                 }
2083                 return true;
2084         }
2085
2086         /* remote ADMIN. leet, huh? */
2087         bool Admin(std::string prefix, std::deque<std::string> &params)
2088         {
2089                 if (params.size() > 0)
2090                 {
2091                         if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
2092                         {
2093                                 /* It's for our server */
2094                                 string_list results;
2095                                 userrec* source = this->Instance->FindNick(prefix);
2096
2097                                 if (source)
2098                                 {
2099                                         std::deque<std::string> par;
2100                                         par.push_back(prefix);
2101                                         par.push_back("");
2102
2103                                         par[1] = std::string("::")+ServerInstance->Config->ServerName+" 256 "+source->nick+" :Administrative info for "+ServerInstance->Config->ServerName;
2104                                         DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2105
2106                                         par[1] = std::string("::")+ServerInstance->Config->ServerName+" 257 "+source->nick+" :Name     - "+ServerInstance->Config->AdminName;
2107                                         DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2108
2109                                         par[1] = std::string("::")+ServerInstance->Config->ServerName+" 258 "+source->nick+" :Nickname - "+ServerInstance->Config->AdminNick;
2110                                         DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2111
2112                                         par[1] = std::string("::")+ServerInstance->Config->ServerName+" 258 "+source->nick+" :E-Mail   - "+ServerInstance->Config->AdminEmail;
2113                                         DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2114                                 }
2115                         }
2116                         else
2117                         {
2118                                 /* Pass it on */
2119                                 userrec* source = this->Instance->FindNick(prefix);
2120                                 if (source)
2121                                         DoOneToOne(prefix, "ADMIN", params, params[0]);
2122                         }
2123                 }
2124                 return true;
2125         }
2126
2127         bool Stats(std::string prefix, std::deque<std::string> &params)
2128         {
2129                 /* Get the reply to a STATS query if it matches this servername,
2130                  * and send it back as a load of PUSH queries
2131                  */
2132                 if (params.size() > 1)
2133                 {
2134                         if (this->Instance->MatchText(this->Instance->Config->ServerName, params[1]))
2135                         {
2136                                 /* It's for our server */
2137                                 string_list results;
2138                                 userrec* source = this->Instance->FindNick(prefix);
2139                                 if (source)
2140                                 {
2141                                         std::deque<std::string> par;
2142                                         par.push_back(prefix);
2143                                         par.push_back("");
2144                                         DoStats(this->Instance, *(params[0].c_str()), source, results);
2145                                         for (size_t i = 0; i < results.size(); i++)
2146                                         {
2147                                                 par[1] = "::" + results[i];
2148                                                 DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2149                                         }
2150                                 }
2151                         }
2152                         else
2153                         {
2154                                 /* Pass it on */
2155                                 userrec* source = this->Instance->FindNick(prefix);
2156                                 if (source)
2157                                         DoOneToOne(prefix, "STATS", params, params[1]);
2158                         }
2159                 }
2160                 return true;
2161         }
2162
2163
2164         /* Because the core won't let users or even SERVERS set +o,
2165          * we use the OPERTYPE command to do this.
2166          */
2167         bool OperType(std::string prefix, std::deque<std::string> &params)
2168         {
2169                 if (params.size() != 1)
2170                 {
2171                         ServerInstance->Log(DEBUG,"Received invalid oper type from %s",prefix.c_str());
2172                         return true;
2173                 }
2174                 std::string opertype = params[0];
2175                 userrec* u = this->Instance->FindNick(prefix);
2176                 if (u)
2177                 {
2178                         u->modes[UM_OPERATOR] = 1;
2179                         strlcpy(u->oper,opertype.c_str(),NICKMAX-1);
2180                         DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
2181                 }
2182                 return true;
2183         }
2184
2185         /* Because Andy insists that services-compatible servers must
2186          * implement SVSNICK and SVSJOIN, that's exactly what we do :p
2187          */
2188         bool ForceNick(std::string prefix, std::deque<std::string> &params)
2189         {
2190                 if (params.size() < 3)
2191                         return true;
2192
2193                 userrec* u = this->Instance->FindNick(params[0]);
2194
2195                 if (u)
2196                 {
2197                         DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
2198                         if (IS_LOCAL(u))
2199                         {
2200                                 std::deque<std::string> par;
2201                                 par.push_back(params[1]);
2202                                 /* This is not required as one is sent in OnUserPostNick below
2203                                  */
2204                                 //DoOneToMany(u->nick,"NICK",par);
2205                                 if (!u->ForceNickChange(params[1].c_str()))
2206                                 {
2207                                         userrec::QuitUser(this->Instance, u, "Nickname collision");
2208                                         return true;
2209                                 }
2210                                 u->age = atoi(params[2].c_str());
2211                         }
2212                 }
2213                 return true;
2214         }
2215
2216         bool ServiceJoin(std::string prefix, std::deque<std::string> &params)
2217         {
2218                 if (params.size() < 2)
2219                         return true;
2220
2221                 userrec* u = this->Instance->FindNick(params[0]);
2222
2223                 if (u)
2224                 {
2225                         chanrec::JoinUser(this->Instance, u, params[1].c_str(), false);
2226                         DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
2227                 }
2228                 return true;
2229         }
2230
2231         bool RemoteRehash(std::string prefix, std::deque<std::string> &params)
2232         {
2233                 if (params.size() < 1)
2234                         return false;
2235
2236                 std::string servermask = params[0];
2237
2238                 if (this->Instance->MatchText(this->Instance->Config->ServerName,servermask))
2239                 {
2240                         this->Instance->SNO->WriteToSnoMask('l',"Remote rehash initiated from server \002"+prefix+"\002.");
2241                         this->Instance->RehashServer();
2242                         ReadConfiguration(false);
2243                 }
2244                 DoOneToAllButSender(prefix,"REHASH",params,prefix);
2245                 return true;
2246         }
2247
2248         bool RemoteKill(std::string prefix, std::deque<std::string> &params)
2249         {
2250                 if (params.size() != 2)
2251                         return true;
2252
2253                 std::string nick = params[0];
2254                 userrec* u = this->Instance->FindNick(prefix);
2255                 userrec* who = this->Instance->FindNick(nick);
2256
2257                 if (who)
2258                 {
2259                         /* Prepend kill source, if we don't have one */
2260                         std::string sourceserv = prefix;
2261                         if (u)
2262                         {
2263                                 sourceserv = u->server;
2264                         }
2265                         if (*(params[1].c_str()) != '[')
2266                         {
2267                                 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
2268                         }
2269                         std::string reason = params[1];
2270                         params[1] = ":" + params[1];
2271                         DoOneToAllButSender(prefix,"KILL",params,sourceserv);
2272                         who->Write(":%s KILL %s :%s (%s)", sourceserv.c_str(), who->nick, sourceserv.c_str(), reason.c_str());
2273                         userrec::QuitUser(this->Instance,who,reason);
2274                 }
2275                 return true;
2276         }
2277
2278         bool LocalPong(std::string prefix, std::deque<std::string> &params)
2279         {
2280                 if (params.size() < 1)
2281                         return true;
2282
2283                 if (params.size() == 1)
2284                 {
2285                         TreeServer* ServerSource = FindServer(prefix);
2286                         if (ServerSource)
2287                         {
2288                                 ServerSource->SetPingFlag();
2289                         }
2290                 }
2291                 else
2292                 {
2293                         std::string forwardto = params[1];
2294                         if (forwardto == this->Instance->Config->ServerName)
2295                         {
2296                                 /*
2297                                  * this is a PONG for us
2298                                  * if the prefix is a user, check theyre local, and if they are,
2299                                  * dump the PONG reply back to their fd. If its a server, do nowt.
2300                                  * Services might want to send these s->s, but we dont need to yet.
2301                                  */
2302                                 userrec* u = this->Instance->FindNick(prefix);
2303
2304                                 if (u)
2305                                 {
2306                                         u->WriteServ("PONG %s %s",params[0].c_str(),params[1].c_str());
2307                                 }
2308                         }
2309                         else
2310                         {
2311                                 // not for us, pass it on :)
2312                                 DoOneToOne(prefix,"PONG",params,forwardto);
2313                         }
2314                 }
2315
2316                 return true;
2317         }
2318         
2319         bool MetaData(std::string prefix, std::deque<std::string> &params)
2320         {
2321                 if (params.size() < 3)
2322                         return true;
2323
2324                 TreeServer* ServerSource = FindServer(prefix);
2325
2326                 if (ServerSource)
2327                 {
2328                         if (params[0] == "*")
2329                         {
2330                                 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
2331                         }
2332                         else if (*(params[0].c_str()) == '#')
2333                         {
2334                                 chanrec* c = this->Instance->FindChan(params[0]);
2335                                 if (c)
2336                                 {
2337                                         FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
2338                                 }
2339                         }
2340                         else if (*(params[0].c_str()) != '#')
2341                         {
2342                                 userrec* u = this->Instance->FindNick(params[0]);
2343                                 if (u)
2344                                 {
2345                                         FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
2346                                 }
2347                         }
2348                 }
2349
2350                 params[2] = ":" + params[2];
2351                 DoOneToAllButSender(prefix,"METADATA",params,prefix);
2352                 return true;
2353         }
2354
2355         bool ServerVersion(std::string prefix, std::deque<std::string> &params)
2356         {
2357                 if (params.size() < 1)
2358                         return true;
2359
2360                 TreeServer* ServerSource = FindServer(prefix);
2361
2362                 if (ServerSource)
2363                 {
2364                         ServerSource->SetVersion(params[0]);
2365                 }
2366                 params[0] = ":" + params[0];
2367                 DoOneToAllButSender(prefix,"VERSION",params,prefix);
2368                 return true;
2369         }
2370
2371         bool ChangeHost(std::string prefix, std::deque<std::string> &params)
2372         {
2373                 if (params.size() < 1)
2374                         return true;
2375
2376                 userrec* u = this->Instance->FindNick(prefix);
2377
2378                 if (u)
2379                 {
2380                         u->ChangeDisplayedHost(params[0].c_str());
2381                         DoOneToAllButSender(prefix,"FHOST",params,u->server);
2382                 }
2383                 return true;
2384         }
2385
2386         bool AddLine(std::string prefix, std::deque<std::string> &params)
2387         {
2388                 if (params.size() < 6)
2389                         return true;
2390
2391                 bool propogate = false;
2392
2393                 switch (*(params[0].c_str()))
2394                 {
2395                         case 'Z':
2396                                 propogate = ServerInstance->XLines->add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2397                                 ServerInstance->XLines->zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2398                         break;
2399                         case 'Q':
2400                                 propogate = ServerInstance->XLines->add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2401                                 ServerInstance->XLines->qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2402                         break;
2403                         case 'E':
2404                                 propogate = ServerInstance->XLines->add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2405                                 ServerInstance->XLines->eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2406                         break;
2407                         case 'G':
2408                                 propogate = ServerInstance->XLines->add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2409                                 ServerInstance->XLines->gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2410                         break;
2411                         case 'K':
2412                                 propogate = ServerInstance->XLines->add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2413                         break;
2414                         default:
2415                                 /* Just in case... */
2416                                 this->Instance->SNO->WriteToSnoMask('x',"\2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");
2417                                 propogate = false;
2418                         break;
2419                 }
2420
2421                 /* Send it on its way */
2422                 if (propogate)
2423                 {
2424                         if (atoi(params[4].c_str()))
2425                         {
2426                                 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());
2427                         }
2428                         else
2429                         {
2430                                 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());
2431                         }
2432                         params[5] = ":" + params[5];
2433                         DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
2434                 }
2435                 if (!this->bursting)
2436                 {
2437                         ServerInstance->Log(DEBUG,"Applying lines...");
2438                         ServerInstance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2439                 }
2440                 return true;
2441         }
2442
2443         bool ChangeName(std::string prefix, std::deque<std::string> &params)
2444         {
2445                 if (params.size() < 1)
2446                         return true;
2447
2448                 userrec* u = this->Instance->FindNick(prefix);
2449
2450                 if (u)
2451                 {
2452                         u->ChangeName(params[0].c_str());
2453                         params[0] = ":" + params[0];
2454                         DoOneToAllButSender(prefix,"FNAME",params,u->server);
2455                 }
2456                 return true;
2457         }
2458
2459         bool Whois(std::string prefix, std::deque<std::string> &params)
2460         {
2461                 if (params.size() < 1)
2462                         return true;
2463
2464                 ServerInstance->Log(DEBUG,"In IDLE command");
2465                 userrec* u = this->Instance->FindNick(prefix);
2466
2467                 if (u)
2468                 {
2469                         ServerInstance->Log(DEBUG,"USER EXISTS: %s",u->nick);
2470                         // an incoming request
2471                         if (params.size() == 1)
2472                         {
2473                                 userrec* x = this->Instance->FindNick(params[0]);
2474                                 if ((x) && (IS_LOCAL(x)))
2475                                 {
2476                                         userrec* x = this->Instance->FindNick(params[0]);
2477                                         ServerInstance->Log(DEBUG,"Got IDLE");
2478                                         char signon[MAXBUF];
2479                                         char idle[MAXBUF];
2480                                         ServerInstance->Log(DEBUG,"Sending back IDLE 3");
2481                                         snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
2482                                         snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-time(NULL)));
2483                                         std::deque<std::string> par;
2484                                         par.push_back(prefix);
2485                                         par.push_back(signon);
2486                                         par.push_back(idle);
2487                                         // ours, we're done, pass it BACK
2488                                         DoOneToOne(params[0],"IDLE",par,u->server);
2489                                 }
2490                                 else
2491                                 {
2492                                         // not ours pass it on
2493                                         DoOneToOne(prefix,"IDLE",params,x->server);
2494                                 }
2495                         }
2496                         else if (params.size() == 3)
2497                         {
2498                                 std::string who_did_the_whois = params[0];
2499                                 userrec* who_to_send_to = this->Instance->FindNick(who_did_the_whois);
2500                                 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2501                                 {
2502                                         ServerInstance->Log(DEBUG,"Got final IDLE");
2503                                         // an incoming reply to a whois we sent out
2504                                         std::string nick_whoised = prefix;
2505                                         unsigned long signon = atoi(params[1].c_str());
2506                                         unsigned long idle = atoi(params[2].c_str());
2507                                         if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2508                                                 do_whois(this->Instance,who_to_send_to,u,signon,idle,nick_whoised.c_str());
2509                                 }
2510                                 else
2511                                 {
2512                                         // not ours, pass it on
2513                                         DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
2514                                 }
2515                         }
2516                 }
2517                 return true;
2518         }
2519
2520         bool Push(std::string prefix, std::deque<std::string> &params)
2521         {
2522                 if (params.size() < 2)
2523                         return true;
2524
2525                 userrec* u = this->Instance->FindNick(params[0]);
2526
2527                 if (!u)
2528                         return true;
2529
2530                 if (IS_LOCAL(u))
2531                 {
2532                         u->Write(params[1]);
2533                 }
2534                 else
2535                 {
2536                         // continue the raw onwards
2537                         params[1] = ":" + params[1];
2538                         DoOneToOne(prefix,"PUSH",params,u->server);
2539                 }
2540                 return true;
2541         }
2542
2543         bool Time(std::string prefix, std::deque<std::string> &params)
2544         {
2545                 // :source.server TIME remote.server sendernick
2546                 // :remote.server TIME source.server sendernick TS
2547                 if (params.size() == 2)
2548                 {
2549                         // someone querying our time?
2550                         if (this->Instance->Config->ServerName == params[0])
2551                         {
2552                                 userrec* u = this->Instance->FindNick(params[1]);
2553                                 if (u)
2554                                 {
2555                                         char curtime[256];
2556                                         snprintf(curtime,256,"%lu",(unsigned long)time(NULL));
2557                                         params.push_back(curtime);
2558                                         params[0] = prefix;
2559                                         DoOneToOne(this->Instance->Config->ServerName,"TIME",params,params[0]);
2560                                 }
2561                         }
2562                         else
2563                         {
2564                                 // not us, pass it on
2565                                 userrec* u = this->Instance->FindNick(params[1]);
2566                                 if (u)
2567                                         DoOneToOne(prefix,"TIME",params,params[0]);
2568                         }
2569                 }
2570                 else if (params.size() == 3)
2571                 {
2572                         // a response to a previous TIME
2573                         userrec* u = this->Instance->FindNick(params[1]);
2574                         if ((u) && (IS_LOCAL(u)))
2575                         {
2576                         time_t rawtime = atol(params[2].c_str());
2577                         struct tm * timeinfo;
2578                         timeinfo = localtime(&rawtime);
2579                                 char tms[26];
2580                                 snprintf(tms,26,"%s",asctime(timeinfo));
2581                                 tms[24] = 0;
2582                         u->WriteServ("391 %s %s :%s",u->nick,prefix.c_str(),tms);
2583                         }
2584                         else
2585                         {
2586                                 if (u)
2587                                         DoOneToOne(prefix,"TIME",params,u->server);
2588                         }
2589                 }
2590                 return true;
2591         }
2592         
2593         bool LocalPing(std::string prefix, std::deque<std::string> &params)
2594         {
2595                 if (params.size() < 1)
2596                         return true;
2597
2598                 if (params.size() == 1)
2599                 {
2600                         std::string stufftobounce = params[0];
2601                         this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" PONG "+stufftobounce);
2602                         return true;
2603                 }
2604                 else
2605                 {
2606                         std::string forwardto = params[1];
2607                         if (forwardto == this->Instance->Config->ServerName)
2608                         {
2609                                 // this is a ping for us, send back PONG to the requesting server
2610                                 params[1] = params[0];
2611                                 params[0] = forwardto;
2612                                 DoOneToOne(forwardto,"PONG",params,params[1]);
2613                         }
2614                         else
2615                         {
2616                                 // not for us, pass it on :)
2617                                 DoOneToOne(prefix,"PING",params,forwardto);
2618                         }
2619                         return true;
2620                 }
2621         }
2622
2623         bool RemoteServer(std::string prefix, std::deque<std::string> &params)
2624         {
2625                 if (params.size() < 4)
2626                         return false;
2627
2628                 std::string servername = params[0];
2629                 std::string password = params[1];
2630                 // hopcount is not used for a remote server, we calculate this ourselves
2631                 std::string description = params[3];
2632                 TreeServer* ParentOfThis = FindServer(prefix);
2633
2634                 if (!ParentOfThis)
2635                 {
2636                         this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
2637                         return false;
2638                 }
2639                 TreeServer* CheckDupe = FindServer(servername);
2640                 if (CheckDupe)
2641                 {
2642                         this->WriteLine("ERROR :Server "+servername+" already exists!");
2643                         this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+servername+"\2 denied, already exists");
2644                         return false;
2645                 }
2646                 TreeServer* Node = new TreeServer(this->Instance,servername,description,ParentOfThis,NULL);
2647                 ParentOfThis->AddChild(Node);
2648                 params[3] = ":" + params[3];
2649                 DoOneToAllButSender(prefix,"SERVER",params,prefix);
2650                 this->Instance->SNO->WriteToSnoMask('l',"Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
2651                 return true;
2652         }
2653
2654         bool Outbound_Reply_Server(std::deque<std::string> &params)
2655         {
2656                 if (params.size() < 4)
2657                         return false;
2658
2659                 irc::string servername = params[0].c_str();
2660                 std::string sname = params[0];
2661                 std::string password = params[1];
2662                 int hops = atoi(params[2].c_str());
2663
2664                 if (hops)
2665                 {
2666                         this->WriteLine("ERROR :Server too far away for authentication");
2667                         this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2668                         return false;
2669                 }
2670                 std::string description = params[3];
2671                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2672                 {
2673                         if ((x->Name == servername) && (x->RecvPass == password))
2674                         {
2675                                 TreeServer* CheckDupe = FindServer(sname);
2676                                 if (CheckDupe)
2677                                 {
2678                                         this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
2679                                         this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
2680                                         return false;
2681                                 }
2682                                 // Begin the sync here. this kickstarts the
2683                                 // other side, waiting in WAIT_AUTH_2 state,
2684                                 // into starting their burst, as it shows
2685                                 // that we're happy.
2686                                 this->LinkState = CONNECTED;
2687                                 // we should add the details of this server now
2688                                 // to the servers tree, as a child of the root
2689                                 // node.
2690                                 TreeServer* Node = new TreeServer(this->Instance,sname,description,TreeRoot,this);
2691                                 TreeRoot->AddChild(Node);
2692                                 params[3] = ":" + params[3];
2693                                 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,sname);
2694                                 this->bursting = true;
2695                                 this->DoBurst(Node);
2696                                 return true;
2697                         }
2698                 }
2699                 this->WriteLine("ERROR :Invalid credentials");
2700                 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
2701                 return false;
2702         }
2703
2704         bool Inbound_Server(std::deque<std::string> &params)
2705         {
2706                 if (params.size() < 4)
2707                         return false;
2708
2709                 irc::string servername = params[0].c_str();
2710                 std::string sname = params[0];
2711                 std::string password = params[1];
2712                 int hops = atoi(params[2].c_str());
2713
2714                 if (hops)
2715                 {
2716                         this->WriteLine("ERROR :Server too far away for authentication");
2717                         this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2718                         return false;
2719                 }
2720                 std::string description = params[3];
2721                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2722                 {
2723                         if ((x->Name == servername) && (x->RecvPass == password))
2724                         {
2725                                 TreeServer* CheckDupe = FindServer(sname);
2726                                 if (CheckDupe)
2727                                 {
2728                                         this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
2729                                         this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
2730                                         return false;
2731                                 }
2732                                 /* If the config says this link is encrypted, but the remote side
2733                                  * hasnt bothered to send the AES command before SERVER, then we
2734                                  * boot them off as we MUST have this connection encrypted.
2735                                  */
2736                                 if ((x->EncryptionKey != "") && (!this->ctx_in))
2737                                 {
2738                                         this->WriteLine("ERROR :This link requires AES encryption to be enabled. Plaintext connection refused.");
2739                                         this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, remote server did not enable AES.");
2740                                         return false;
2741                                 }
2742                                 this->Instance->SNO->WriteToSnoMask('l',"Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
2743                                 this->InboundServerName = sname;
2744                                 this->InboundDescription = description;
2745                                 // this is good. Send our details: Our server name and description and hopcount of 0,
2746                                 // along with the sendpass from this block.
2747                                 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+x->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
2748                                 // move to the next state, we are now waiting for THEM.
2749                                 this->LinkState = WAIT_AUTH_2;
2750                                 return true;
2751                         }
2752                 }
2753                 this->WriteLine("ERROR :Invalid credentials");
2754                 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
2755                 return false;
2756         }
2757
2758         void Split(std::string line, std::deque<std::string> &n)
2759         {
2760                 n.clear();
2761                 irc::tokenstream tokens(line);
2762                 std::string param;
2763                 while ((param = tokens.GetToken()) != "")
2764                         n.push_back(param);
2765                 return;
2766         }
2767
2768         bool ProcessLine(std::string line)
2769         {
2770                 std::deque<std::string> params;
2771                 irc::string command;
2772                 std::string prefix;
2773                 
2774                 if (line.empty())
2775                         return true;
2776                 
2777                 line = line.substr(0, line.find_first_of("\r\n"));
2778                 
2779                 ServerInstance->Log(DEBUG,"IN: %s", line.c_str());
2780                 
2781                 this->Split(line.c_str(),params);
2782                         
2783                 if ((params[0][0] == ':') && (params.size() > 1))
2784                 {
2785                         prefix = params[0].substr(1);
2786                         params.pop_front();
2787                 }
2788
2789                 command = params[0].c_str();
2790                 params.pop_front();
2791
2792                 if ((!this->ctx_in) && (command == "AES"))
2793                 {
2794                         std::string sserv = params[0];
2795                         for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2796                         {
2797                                 if ((x->EncryptionKey != "") && (x->Name == sserv))
2798                                 {
2799                                         this->InitAES(x->EncryptionKey,sserv);
2800                                 }
2801                         }
2802
2803                         return true;
2804                 }
2805                 else if ((this->ctx_in) && (command == "AES"))
2806                 {
2807                         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());
2808                 }
2809
2810                 switch (this->LinkState)
2811                 {
2812                         TreeServer* Node;
2813                         
2814                         case WAIT_AUTH_1:
2815                                 // Waiting for SERVER command from remote server. Server initiating
2816                                 // the connection sends the first SERVER command, listening server
2817                                 // replies with theirs if its happy, then if the initiator is happy,
2818                                 // it starts to send its net sync, which starts the merge, otherwise
2819                                 // it sends an ERROR.
2820                                 if (command == "PASS")
2821                                 {
2822                                         /* Silently ignored */
2823                                 }
2824                                 else if (command == "SERVER")
2825                                 {
2826                                         return this->Inbound_Server(params);
2827                                 }
2828                                 else if (command == "ERROR")
2829                                 {
2830                                         return this->Error(params);
2831                                 }
2832                                 else if (command == "USER")
2833                                 {
2834                                         this->WriteLine("ERROR :Client connections to this port are prohibited.");
2835                                         return false;
2836                                 }
2837                                 else if (command == "CAPAB")
2838                                 {
2839                                         return this->Capab(params);
2840                                 }
2841                                 else if ((command == "U") || (command == "S"))
2842                                 {
2843                                         this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
2844                                         return false;
2845                                 }
2846                                 else
2847                                 {
2848                                         this->WriteLine("ERROR :Invalid command in negotiation phase.");
2849                                         return false;
2850                                 }
2851                         break;
2852                         case WAIT_AUTH_2:
2853                                 // Waiting for start of other side's netmerge to say they liked our
2854                                 // password.
2855                                 if (command == "SERVER")
2856                                 {
2857                                         // cant do this, they sent it to us in the WAIT_AUTH_1 state!
2858                                         // silently ignore.
2859                                         return true;
2860                                 }
2861                                 else if ((command == "U") || (command == "S"))
2862                                 {
2863                                         this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
2864                                         return false;
2865                                 }
2866                                 else if (command == "BURST")
2867                                 {
2868                                         if (params.size())
2869                                         {
2870                                                 /* If a time stamp is provided, try and check syncronization */
2871                                                 time_t THEM = atoi(params[0].c_str());
2872                                                 long delta = THEM-time(NULL);
2873                                                 if ((delta < -600) || (delta > 600))
2874                                                 {
2875                                                         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));
2876                                                         this->WriteLine("ERROR :Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than ten minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
2877                                                         return false;
2878                                                 }
2879                                                 else if ((delta < -60) || (delta > 60))
2880                                                 {
2881                                                         this->Instance->SNO->WriteToSnoMask('l',"\2WARNING\2: Your clocks are out by %d seconds, please consider synching your clocks.",abs(delta));
2882                                                 }
2883                                         }
2884                                         this->LinkState = CONNECTED;
2885                                         Node = new TreeServer(this->Instance,InboundServerName,InboundDescription,TreeRoot,this);
2886                                         TreeRoot->AddChild(Node);
2887                                         params.clear();
2888                                         params.push_back(InboundServerName);
2889                                         params.push_back("*");
2890                                         params.push_back("1");
2891                                         params.push_back(":"+InboundDescription);
2892                                         DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
2893                                         this->bursting = true;
2894                                         this->DoBurst(Node);
2895                                 }
2896                                 else if (command == "ERROR")
2897                                 {
2898                                         return this->Error(params);
2899                                 }
2900                                 else if (command == "CAPAB")
2901                                 {
2902                                         return this->Capab(params);
2903                                 }
2904                                 
2905                         break;
2906                         case LISTENER:
2907                                 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
2908                                 return false;
2909                         break;
2910                         case CONNECTING:
2911                                 if (command == "SERVER")
2912                                 {
2913                                         // another server we connected to, which was in WAIT_AUTH_1 state,
2914                                         // has just sent us their credentials. If we get this far, theyre
2915                                         // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
2916                                         // if we're happy with this, we should send our netburst which
2917                                         // kickstarts the merge.
2918                                         return this->Outbound_Reply_Server(params);
2919                                 }
2920                                 else if (command == "ERROR")
2921                                 {
2922                                         return this->Error(params);
2923                                 }
2924                         break;
2925                         case CONNECTED:
2926                                 // This is the 'authenticated' state, when all passwords
2927                                 // have been exchanged and anything past this point is taken
2928                                 // as gospel.
2929                                 
2930                                 if (prefix != "")
2931                                 {
2932                                         std::string direction = prefix;
2933                                         userrec* t = this->Instance->FindNick(prefix);
2934                                         if (t)
2935                                         {
2936                                                 direction = t->server;
2937                                         }
2938                                         TreeServer* route_back_again = BestRouteTo(direction);
2939                                         if ((!route_back_again) || (route_back_again->GetSocket() != this))
2940                                         {
2941                                                 if (route_back_again)
2942                                                         ServerInstance->Log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
2943                                                 return true;
2944                                         }
2945
2946                                         /* Fix by brain:
2947                                          * When there is activity on the socket, reset the ping counter so
2948                                          * that we're not wasting bandwidth pinging an active server.
2949                                          */ 
2950                                         route_back_again->SetNextPingTime(time(NULL) + 60);
2951                                         route_back_again->SetPingFlag();
2952                                 }
2953                                 
2954                                 if (command == "SVSMODE")
2955                                 {
2956                                         /* Services expects us to implement
2957                                          * SVSMODE. In inspircd its the same as
2958                                          * MODE anyway.
2959                                          */
2960                                         command = "MODE";
2961                                 }
2962                                 std::string target = "";
2963                                 /* Yes, know, this is a mess. Its reasonably fast though as we're
2964                                  * working with std::string here.
2965                                  */
2966                                 if ((command == "NICK") && (params.size() > 1))
2967                                 {
2968                                         return this->IntroduceClient(prefix,params);
2969                                 }
2970                                 else if (command == "FJOIN")
2971                                 {
2972                                         return this->ForceJoin(prefix,params);
2973                                 }
2974                                 else if (command == "STATS")
2975                                 {
2976                                         return this->Stats(prefix, params);
2977                                 }
2978                                 else if (command == "MOTD")
2979                                 {
2980                                         return this->Motd(prefix, params);
2981                                 }
2982                                 else if (command == "ADMIN")
2983                                 {
2984                                         return this->Admin(prefix, params);
2985                                 }
2986                                 else if (command == "SERVER")
2987                                 {
2988                                         return this->RemoteServer(prefix,params);
2989                                 }
2990                                 else if (command == "ERROR")
2991                                 {
2992                                         return this->Error(params);
2993                                 }
2994                                 else if (command == "OPERTYPE")
2995                                 {
2996                                         return this->OperType(prefix,params);
2997                                 }
2998                                 else if (command == "FMODE")
2999                                 {
3000                                         return this->ForceMode(prefix,params);
3001                                 }
3002                                 else if (command == "KILL")
3003                                 {
3004                                         return this->RemoteKill(prefix,params);
3005                                 }
3006                                 else if (command == "FTOPIC")
3007                                 {
3008                                         return this->ForceTopic(prefix,params);
3009                                 }
3010                                 else if (command == "REHASH")
3011                                 {
3012                                         return this->RemoteRehash(prefix,params);
3013                                 }
3014                                 else if (command == "METADATA")
3015                                 {
3016                                         return this->MetaData(prefix,params);
3017                                 }
3018                                 else if (command == "PING")
3019                                 {
3020                                         /*
3021                                          * We just got a ping from a server that's bursting.
3022                                          * This can't be right, so set them to not bursting, and
3023                                          * apply their lines.
3024                                          */
3025                                         if (this->bursting)
3026                                         {
3027                                                 this->bursting = false;
3028                                                 ServerInstance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3029                                         }
3030                                         if (prefix == "")
3031                                         {
3032                                                 prefix = this->GetName();
3033                                         }
3034                                         return this->LocalPing(prefix,params);
3035                                 }
3036                                 else if (command == "PONG")
3037                                 {
3038                                         /*
3039                                          * We just got a pong from a server that's bursting.
3040                                          * This can't be right, so set them to not bursting, and
3041                                          * apply their lines.
3042                                          */
3043                                         if (this->bursting)
3044                                         {
3045                                                 this->bursting = false;
3046                                                 ServerInstance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3047                                         }
3048                                         if (prefix == "")
3049                                         {
3050                                                 prefix = this->GetName();
3051                                         }
3052                                         return this->LocalPong(prefix,params);
3053                                 }
3054                                 else if (command == "VERSION")
3055                                 {
3056                                         return this->ServerVersion(prefix,params);
3057                                 }
3058                                 else if (command == "FHOST")
3059                                 {
3060                                         return this->ChangeHost(prefix,params);
3061                                 }
3062                                 else if (command == "FNAME")
3063                                 {
3064                                         return this->ChangeName(prefix,params);
3065                                 }
3066                                 else if (command == "ADDLINE")
3067                                 {
3068                                         return this->AddLine(prefix,params);
3069                                 }
3070                                 else if (command == "SVSNICK")
3071                                 {
3072                                         if (prefix == "")
3073                                         {
3074                                                 prefix = this->GetName();
3075                                         }
3076                                         return this->ForceNick(prefix,params);
3077                                 }
3078                                 else if (command == "IDLE")
3079                                 {
3080                                         return this->Whois(prefix,params);
3081                                 }
3082                                 else if (command == "PUSH")
3083                                 {
3084                                         return this->Push(prefix,params);
3085                                 }
3086                                 else if (command == "TIME")
3087                                 {
3088                                         return this->Time(prefix,params);
3089                                 }
3090                                 else if ((command == "KICK") && (IsServer(prefix)))
3091                                 {
3092                                         std::string sourceserv = this->myhost;
3093                                         if (params.size() == 3)
3094                                         {
3095                                                 userrec* user = this->Instance->FindNick(params[1]);
3096                                                 chanrec* chan = this->Instance->FindChan(params[0]);
3097                                                 if (user && chan)
3098                                                 {
3099                                                         if (!chan->ServerKickUser(user, params[2].c_str(), false))
3100                                                                 /* Yikes, the channels gone! */
3101                                                                 delete chan;
3102                                                 }
3103                                         }
3104                                         if (this->InboundServerName != "")
3105                                         {
3106                                                 sourceserv = this->InboundServerName;
3107                                         }
3108                                         return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3109                                 }
3110                                 else if (command == "SVSJOIN")
3111                                 {
3112                                         if (prefix == "")
3113                                         {
3114                                                 prefix = this->GetName();
3115                                         }
3116                                         return this->ServiceJoin(prefix,params);
3117                                 }
3118                                 else if (command == "SQUIT")
3119                                 {
3120                                         if (params.size() == 2)
3121                                         {
3122                                                 this->Squit(FindServer(params[0]),params[1]);
3123                                         }
3124                                         return true;
3125                                 }
3126                                 else if (command == "ENDBURST")
3127                                 {
3128                                         this->bursting = false;
3129                                         ServerInstance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3130                                         std::string sourceserv = this->myhost;
3131                                         if (this->InboundServerName != "")
3132                                         {
3133                                                 sourceserv = this->InboundServerName;
3134                                         }
3135                                         this->Instance->SNO->WriteToSnoMask('l',"Received end of netburst from \2%s\2",sourceserv.c_str());
3136                                         return true;
3137                                 }
3138                                 else
3139                                 {
3140                                         // not a special inter-server command.
3141                                         // Emulate the actual user doing the command,
3142                                         // this saves us having a huge ugly parser.
3143                                         userrec* who = this->Instance->FindNick(prefix);
3144                                         std::string sourceserv = this->myhost;
3145                                         if (this->InboundServerName != "")
3146                                         {
3147                                                 sourceserv = this->InboundServerName;
3148                                         }
3149                                         if (who)
3150                                         {
3151                                                 if ((command == "NICK") && (params.size() > 0))
3152                                                 {
3153                                                         /* On nick messages, check that the nick doesnt
3154                                                          * already exist here. If it does, kill their copy,
3155                                                          * and our copy.
3156                                                          */
3157                                                         userrec* x = this->Instance->FindNick(params[0]);
3158                                                         if ((x) && (x != who))
3159                                                         {
3160                                                                 std::deque<std::string> p;
3161                                                                 p.push_back(params[0]);
3162                                                                 p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
3163                                                                 DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
3164                                                                 p.clear();
3165                                                                 p.push_back(prefix);
3166                                                                 p.push_back("Nickname collision");
3167                                                                 DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
3168                                                                 userrec::QuitUser(this->Instance,x,"Nickname collision ("+prefix+" -> "+params[0]+")");
3169                                                                 userrec* y = this->Instance->FindNick(prefix);
3170                                                                 if (y)
3171                                                                 {
3172                                                                         userrec::QuitUser(this->Instance,y,"Nickname collision");
3173                                                                 }
3174                                                                 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3175                                                         }
3176                                                 }
3177                                                 // its a user
3178                                                 target = who->server;
3179                                                 const char* strparams[127];
3180                                                 for (unsigned int q = 0; q < params.size(); q++)
3181                                                 {
3182                                                         strparams[q] = params[q].c_str();
3183                                                 }
3184                                                 if (!this->Instance->CallCommandHandler(command.c_str(), strparams, params.size(), who))
3185                                                 {
3186                                                         this->WriteLine("ERROR :Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
3187                                                         return false;
3188                                                 }
3189                                         }
3190                                         else
3191                                         {
3192                                                 // its not a user. Its either a server, or somethings screwed up.
3193                                                 if (IsServer(prefix))
3194                                                 {
3195                                                         target = this->Instance->Config->ServerName;
3196                                                 }
3197                                                 else
3198                                                 {
3199                                                         ServerInstance->Log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
3200                                                         return true;
3201                                                 }
3202                                         }
3203                                         return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3204
3205                                 }
3206                                 return true;
3207                         break;
3208                 }
3209                 return true;
3210         }
3211
3212         virtual std::string GetName()
3213         {
3214                 std::string sourceserv = this->myhost;
3215                 if (this->InboundServerName != "")
3216                 {
3217                         sourceserv = this->InboundServerName;
3218                 }
3219                 return sourceserv;
3220         }
3221
3222         virtual void OnTimeout()
3223         {
3224                 if (this->LinkState == CONNECTING)
3225                 {
3226                         this->Instance->SNO->WriteToSnoMask('l',"CONNECT: Connection to \002"+myhost+"\002 timed out.");
3227                         Link* MyLink = FindLink(myhost);
3228                         if (MyLink)
3229                                 DoFailOver(MyLink);
3230                 }
3231         }
3232
3233         virtual void OnClose()
3234         {
3235                 // Connection closed.
3236                 // If the connection is fully up (state CONNECTED)
3237                 // then propogate a netsplit to all peers.
3238                 std::string quitserver = this->myhost;
3239                 if (this->InboundServerName != "")
3240                 {
3241                         quitserver = this->InboundServerName;
3242                 }
3243                 TreeServer* s = FindServer(quitserver);
3244                 if (s)
3245                 {
3246                         Squit(s,"Remote host closed the connection");
3247                 }
3248                 this->Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' failed.",quitserver.c_str());
3249         }
3250
3251         virtual int OnIncomingConnection(int newsock, char* ip)
3252         {
3253                 /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
3254                  * or discovering if this port is the server port, we don't allow connections from any
3255                  * IPs for which we don't have a link block.
3256                  */
3257                 bool found = false;
3258
3259                 found = (std::find(ValidIPs.begin(), ValidIPs.end(), ip) != ValidIPs.end());
3260                 if (!found)
3261                 {
3262                         for (vector<std::string>::iterator i = ValidIPs.begin(); i != ValidIPs.end(); i++)
3263                                 if (MatchCIDR(ip, (*i).c_str()))
3264                                         found = true;
3265
3266                         if (!found)
3267                         {
3268                                 this->Instance->SNO->WriteToSnoMask('l',"Server connection from %s denied (no link blocks with that IP address)", ip);
3269                                 close(newsock);
3270                                 return false;
3271                         }
3272                 }
3273                 TreeSocket* s = new TreeSocket(this->Instance, newsock, ip);
3274                 s = s; /* Whinge whinge whinge, thats all GCC ever does. */
3275                 return true;
3276         }
3277 };
3278
3279 /** This class is used to resolve server hostnames during /connect and autoconnect.
3280  * As of 1.1, the resolver system is seperated out from InspSocket, so we must do this
3281  * resolver step first ourselves if we need it. This is totally nonblocking, and will
3282  * callback to OnLookupComplete or OnError when completed. Once it has completed we
3283  * will have an IP address which we can then use to continue our connection.
3284  */
3285 class ServernameResolver : public Resolver
3286 {       
3287  private:
3288         /** A copy of the Link tag info for what we're connecting to.
3289          * We take a copy, rather than using a pointer, just in case the
3290          * admin takes the tag away and rehashes while the domain is resolving.
3291          */
3292         Link MyLink;
3293  public: 
3294         ServernameResolver(InspIRCd* Instance, const std::string &hostname, Link x) : Resolver(Instance, hostname, DNS_QUERY_FORWARD), MyLink(x)
3295         {
3296                 /* Nothing in here, folks */
3297         }
3298
3299         void OnLookupComplete(const std::string &result)
3300         {
3301                 /* Initiate the connection, now that we have an IP to use.
3302                  * Passing a hostname directly to InspSocket causes it to
3303                  * just bail and set its FD to -1.
3304                  */
3305                 TreeServer* CheckDupe = FindServer(MyLink.Name.c_str());
3306                 if (!CheckDupe) /* Check that nobody tried to connect it successfully while we were resolving */
3307                 {
3308                         TreeSocket* newsocket = new TreeSocket(ServerInstance, result,MyLink.Port,false,10,MyLink.Name.c_str());
3309                         if (newsocket->GetFd() > -1)
3310                         {
3311                                 /* We're all OK */
3312                         }
3313                         else
3314                         {
3315                                 /* Something barfed, show the opers */
3316                                 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",MyLink.Name.c_str(),strerror(errno));
3317                                 delete newsocket;
3318                                 DoFailOver(&MyLink);
3319                         }
3320                 }
3321         }
3322
3323         void OnError(ResolverError e, const std::string &errormessage)
3324         {
3325                 /* Ooops! */
3326                 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: Unable to resolve hostname - %s",MyLink.Name.c_str(),errormessage.c_str());
3327                 DoFailOver(&MyLink);
3328         }
3329 };
3330
3331 class SecurityIPResolver : public Resolver
3332 {
3333  private:
3334         Link MyLink;
3335  public:
3336         SecurityIPResolver(InspIRCd* Instance, const std::string &hostname, Link x) : Resolver(Instance, hostname, DNS_QUERY_FORWARD), MyLink(x)
3337         {
3338         }
3339
3340         void OnLookupComplete(const std::string &result)
3341         {
3342                 ServerInstance->Log(DEBUG,"Security IP cache: Adding IP address '%s' for Link '%s'",result.c_str(),MyLink.Name.c_str());
3343                 ValidIPs.push_back(result);
3344         }
3345
3346         void OnError(ResolverError e, const std::string &errormessage)
3347         {
3348                 ServerInstance->Log(DEBUG,"Could not resolve IP associated with Link '%s': %s",MyLink.Name.c_str(),errormessage.c_str());
3349         }
3350 };
3351
3352 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
3353 {
3354         for (unsigned int c = 0; c < list.size(); c++)
3355         {
3356                 if (list[c] == server)
3357                 {
3358                         return;
3359                 }
3360         }
3361         list.push_back(server);
3362 }
3363
3364 // returns a list of DIRECT servernames for a specific channel
3365 void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
3366 {
3367         CUList *ulist = c->GetUsers();
3368         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
3369         {
3370                 if (i->second->GetFd() < 0)
3371                 {
3372                         TreeServer* best = BestRouteTo(i->second->server);
3373                         if (best)
3374                                 AddThisServer(best,list);
3375                 }
3376         }
3377         return;
3378 }
3379
3380 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, irc::string command, std::deque<std::string> &params)
3381 {
3382         TreeServer* omitroute = BestRouteTo(omit);
3383         if ((command == "NOTICE") || (command == "PRIVMSG"))
3384         {
3385                 if (params.size() >= 2)
3386                 {
3387                         /* Prefixes */
3388                         if ((*(params[0].c_str()) == '@') || (*(params[0].c_str()) == '%') || (*(params[0].c_str()) == '+'))
3389                         {
3390                                 params[0] = params[0].substr(1, params[0].length()-1);
3391                         }
3392                         if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$'))
3393                         {
3394                                 // special routing for private messages/notices
3395                                 userrec* d = ServerInstance->FindNick(params[0]);
3396                                 if (d)
3397                                 {
3398                                         std::deque<std::string> par;
3399                                         par.push_back(params[0]);
3400                                         par.push_back(":"+params[1]);
3401                                         DoOneToOne(prefix,command.c_str(),par,d->server);
3402                                         return true;
3403                                 }
3404                         }
3405                         else if (*(params[0].c_str()) == '$')
3406                         {
3407                                 std::deque<std::string> par;
3408                                 par.push_back(params[0]);
3409                                 par.push_back(":"+params[1]);
3410                                 DoOneToAllButSender(prefix,command.c_str(),par,omitroute->GetName());
3411                                 return true;
3412                         }
3413                         else
3414                         {
3415                                 ServerInstance->Log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
3416                                 chanrec* c = ServerInstance->FindChan(params[0]);
3417                                 if (c)
3418                                 {
3419                                         std::deque<TreeServer*> list;
3420                                         GetListOfServersForChannel(c,list);
3421                                         ServerInstance->Log(DEBUG,"Got a list of %d servers",list.size());
3422                                         unsigned int lsize = list.size();
3423                                         for (unsigned int i = 0; i < lsize; i++)
3424                                         {
3425                                                 TreeSocket* Sock = list[i]->GetSocket();
3426                                                 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
3427                                                 {
3428                                                         ServerInstance->Log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
3429                                                         Sock->WriteLine(data);
3430                                                 }
3431                                         }
3432                                         return true;
3433                                 }
3434                         }
3435                 }
3436         }
3437         unsigned int items = TreeRoot->ChildCount();
3438         for (unsigned int x = 0; x < items; x++)
3439         {
3440                 TreeServer* Route = TreeRoot->GetChild(x);
3441                 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3442                 {
3443                         TreeSocket* Sock = Route->GetSocket();
3444                         if (Sock)
3445                                 Sock->WriteLine(data);
3446                 }
3447         }
3448         return true;
3449 }
3450
3451 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> &params, std::string omit)
3452 {
3453         TreeServer* omitroute = BestRouteTo(omit);
3454         std::string FullLine = ":" + prefix + " " + command;
3455         unsigned int words = params.size();
3456         for (unsigned int x = 0; x < words; x++)
3457         {
3458                 FullLine = FullLine + " " + params[x];
3459         }
3460         unsigned int items = TreeRoot->ChildCount();
3461         for (unsigned int x = 0; x < items; x++)
3462         {
3463                 TreeServer* Route = TreeRoot->GetChild(x);
3464                 // Send the line IF:
3465                 // The route has a socket (its a direct connection)
3466                 // The route isnt the one to be omitted
3467                 // The route isnt the path to the one to be omitted
3468                 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3469                 {
3470                         TreeSocket* Sock = Route->GetSocket();
3471                         if (Sock)
3472                                 Sock->WriteLine(FullLine);
3473                 }
3474         }
3475         return true;
3476 }
3477
3478 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> &params)
3479 {
3480         std::string FullLine = ":" + prefix + " " + command;
3481         unsigned int words = params.size();
3482         for (unsigned int x = 0; x < words; x++)
3483         {
3484                 FullLine = FullLine + " " + params[x];
3485         }
3486         unsigned int items = TreeRoot->ChildCount();
3487         for (unsigned int x = 0; x < items; x++)
3488         {
3489                 TreeServer* Route = TreeRoot->GetChild(x);
3490                 if (Route && Route->GetSocket())
3491                 {
3492                         TreeSocket* Sock = Route->GetSocket();
3493                         if (Sock)
3494                                 Sock->WriteLine(FullLine);
3495                 }
3496         }
3497         return true;
3498 }
3499
3500 bool DoOneToMany(const char* prefix, const char* command, std::deque<std::string> &params)
3501 {
3502         std::string spfx = prefix;
3503         std::string scmd = command;
3504         return DoOneToMany(spfx, scmd, params);
3505 }
3506
3507 bool DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> &params, std::string omit)
3508 {
3509         std::string spfx = prefix;
3510         std::string scmd = command;
3511         return DoOneToAllButSender(spfx, scmd, params, omit);
3512 }
3513
3514 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> &params, std::string target)
3515 {
3516         TreeServer* Route = BestRouteTo(target);
3517         if (Route)
3518         {
3519                 std::string FullLine = ":" + prefix + " " + command;
3520                 unsigned int words = params.size();
3521                 for (unsigned int x = 0; x < words; x++)
3522                 {
3523                         FullLine = FullLine + " " + params[x];
3524                 }
3525                 if (Route && Route->GetSocket())
3526                 {
3527                         TreeSocket* Sock = Route->GetSocket();
3528                         if (Sock)
3529                                 Sock->WriteLine(FullLine);
3530                 }
3531                 return true;
3532         }
3533         else
3534         {
3535                 return false;
3536         }
3537 }
3538
3539 std::vector<TreeSocket*> Bindings;
3540
3541 void ReadConfiguration(bool rebind)
3542 {
3543         Conf = new ConfigReader(ServerInstance);
3544         if (rebind)
3545         {
3546                 for (int j =0; j < Conf->Enumerate("bind"); j++)
3547                 {
3548                         std::string Type = Conf->ReadValue("bind","type",j);
3549                         std::string IP = Conf->ReadValue("bind","address",j);
3550                         long Port = Conf->ReadInteger("bind","port",j,true);
3551                         if (Type == "servers")
3552                         {
3553                                 if (IP == "*")
3554                                 {
3555                                         IP = "";
3556                                 }
3557                                 TreeSocket* listener = new TreeSocket(ServerInstance, IP.c_str(),Port,true,10);
3558                                 if (listener->GetState() == I_LISTENING)
3559                                 {
3560                                         Bindings.push_back(listener);
3561                                 }
3562                                 else
3563                                 {
3564                                         ServerInstance->Log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
3565                                         listener->Close();
3566                                         DELETE(listener);
3567                                 }
3568                         }
3569                 }
3570         }
3571         FlatLinks = Conf->ReadFlag("options","flatlinks",0);
3572         HideULines = Conf->ReadFlag("options","hideulines",0);
3573         LinkBlocks.clear();
3574         ValidIPs.clear();
3575         for (int j =0; j < Conf->Enumerate("link"); j++)
3576         {
3577                 Link L;
3578                 std::string Allow = Conf->ReadValue("link","allowmask",j);
3579                 L.Name = (Conf->ReadValue("link","name",j)).c_str();
3580                 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
3581                 L.FailOver = Conf->ReadValue("link","failover",j).c_str();
3582                 L.Port = Conf->ReadInteger("link","port",j,true);
3583                 L.SendPass = Conf->ReadValue("link","sendpass",j);
3584                 L.RecvPass = Conf->ReadValue("link","recvpass",j);
3585                 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
3586                 L.EncryptionKey =  Conf->ReadValue("link","encryptionkey",j);
3587                 L.HiddenFromStats = Conf->ReadFlag("link","hidden",j);
3588                 L.NextConnectTime = time(NULL) + L.AutoConnect;
3589                 /* Bugfix by brain, do not allow people to enter bad configurations */
3590                 if (L.Name != ServerInstance->Config->ServerName)
3591                 {
3592                         if ((L.IPAddr != "") && (L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
3593                         {
3594                                 ValidIPs.push_back(L.IPAddr);
3595
3596                                 if (Allow.length())
3597                                         ValidIPs.push_back(Allow);
3598
3599                                 /* Needs resolving */
3600                                 insp_inaddr binip;
3601                                 if (insp_aton(L.IPAddr.c_str(), &binip) < 1)
3602                                 {
3603                                         try
3604                                         {
3605                                                 SecurityIPResolver* sr = new SecurityIPResolver(ServerInstance, L.IPAddr, L);
3606                                                 ServerInstance->AddResolver(sr);
3607                                         }
3608                                         catch (ModuleException& e)
3609                                         {
3610                                                 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
3611                                         }
3612                                 }
3613
3614                                 LinkBlocks.push_back(L);
3615                                 ServerInstance->Log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
3616                         }
3617                         else
3618                         {
3619                                 if (L.IPAddr == "")
3620                                 {
3621                                         ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', IP address not defined!",L.Name.c_str());
3622                                 }
3623                                 else if (L.RecvPass == "")
3624                                 {
3625                                         ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', recvpass not defined!",L.Name.c_str());
3626                                 }
3627                                 else if (L.SendPass == "")
3628                                 {
3629                                         ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', sendpass not defined!",L.Name.c_str());
3630                                 }
3631                                 else if (L.Name == "")
3632                                 {
3633                                         ServerInstance->Log(DEFAULT,"Invalid configuration, link tag without a name!");
3634                                 }
3635                                 else if (!L.Port)
3636                                 {
3637                                         ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', no port specified!",L.Name.c_str());
3638                                 }
3639                         }
3640                 }
3641                 else
3642                 {
3643                         ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', link tag has the same server name as the local server!",L.Name.c_str());
3644                 }
3645         }
3646         DELETE(Conf);
3647 }
3648
3649
3650 class ModuleSpanningTree : public Module
3651 {
3652         std::vector<TreeSocket*> Bindings;
3653         int line;
3654         int NumServers;
3655         unsigned int max_local;
3656         unsigned int max_global;
3657         cmd_rconnect* command_rconnect;
3658
3659  public:
3660
3661         ModuleSpanningTree(InspIRCd* Me)
3662                 : Module::Module(Me), max_local(0), max_global(0)
3663         {
3664                 
3665                 Bindings.clear();
3666
3667                 ::ServerInstance = Me;
3668
3669                 // Create the root of the tree
3670                 TreeRoot = new TreeServer(ServerInstance, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc);
3671
3672                 ReadConfiguration(true);
3673
3674                 command_rconnect = new cmd_rconnect(ServerInstance, this);
3675                 ServerInstance->AddCommand(command_rconnect);
3676         }
3677
3678         void ShowLinks(TreeServer* Current, userrec* user, int hops)
3679         {
3680                 std::string Parent = TreeRoot->GetName();
3681                 if (Current->GetParent())
3682                 {
3683                         Parent = Current->GetParent()->GetName();
3684                 }
3685                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
3686                 {
3687                         if ((HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str())))
3688                         {
3689                                 if (*user->oper)
3690                                 {
3691                                          ShowLinks(Current->GetChild(q),user,hops+1);
3692                                 }
3693                         }
3694                         else
3695                         {
3696                                 ShowLinks(Current->GetChild(q),user,hops+1);
3697                         }
3698                 }
3699                 /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
3700                 if ((HideULines) && (ServerInstance->ULine(Current->GetName().c_str())) && (!*user->oper))
3701                         return;
3702                 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());
3703         }
3704
3705         int CountLocalServs()
3706         {
3707                 return TreeRoot->ChildCount();
3708         }
3709
3710         int CountServs()
3711         {
3712                 return serverlist.size();
3713         }
3714
3715         void HandleLinks(const char** parameters, int pcnt, userrec* user)
3716         {
3717                 ShowLinks(TreeRoot,user,0);
3718                 user->WriteServ("365 %s * :End of /LINKS list.",user->nick);
3719                 return;
3720         }
3721
3722         void HandleLusers(const char** parameters, int pcnt, userrec* user)
3723         {
3724                 unsigned int n_users = ServerInstance->UserCount();
3725
3726                 /* Only update these when someone wants to see them, more efficient */
3727                 if ((unsigned int)ServerInstance->LocalUserCount() > max_local)
3728                         max_local = ServerInstance->LocalUserCount();
3729                 if (n_users > max_global)
3730                         max_global = n_users;
3731
3732                 user->WriteServ("251 %s :There are %d users and %d invisible on %d servers",user->nick,n_users-ServerInstance->InvisibleUserCount(),ServerInstance->InvisibleUserCount(),this->CountServs());
3733                 if (ServerInstance->OperCount())
3734                         user->WriteServ("252 %s %d :operator(s) online",user->nick,ServerInstance->OperCount());
3735                 if (ServerInstance->UnregisteredUserCount())
3736                         user->WriteServ("253 %s %d :unknown connections",user->nick,ServerInstance->UnregisteredUserCount());
3737                 if (ServerInstance->ChannelCount())
3738                         user->WriteServ("254 %s %d :channels formed",user->nick,ServerInstance->ChannelCount());
3739                 user->WriteServ("254 %s :I have %d clients and %d servers",user->nick,ServerInstance->LocalUserCount(),this->CountLocalServs());
3740                 user->WriteServ("265 %s :Current Local Users: %d  Max: %d",user->nick,ServerInstance->LocalUserCount(),max_local);
3741                 user->WriteServ("266 %s :Current Global Users: %d  Max: %d",user->nick,n_users,max_global);
3742                 return;
3743         }
3744
3745         // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
3746
3747         void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80], float &totusers, float &totservers)
3748         {
3749                 if (line < 128)
3750                 {
3751                         for (int t = 0; t < depth; t++)
3752                         {
3753                                 matrix[line][t] = ' ';
3754                         }
3755
3756                         // For Aligning, we need to work out exactly how deep this thing is, and produce
3757                         // a 'Spacer' String to compensate.
3758                         char spacer[40];
3759
3760                         memset(spacer,' ',40);
3761                         if ((40 - Current->GetName().length() - depth) > 1) {
3762                                 spacer[40 - Current->GetName().length() - depth] = '\0';
3763                         }
3764                         else
3765                         {
3766                                 spacer[5] = '\0';
3767                         }
3768
3769                         float percent;
3770                         char text[80];
3771                         if (ServerInstance->clientlist.size() == 0) {
3772                                 // If there are no users, WHO THE HELL DID THE /MAP?!?!?!
3773                                 percent = 0;
3774                         }
3775                         else
3776                         {
3777                                 percent = ((float)Current->GetUserCount() / (float)ServerInstance->clientlist.size()) * 100;
3778                         }
3779                         snprintf(text, 80, "%s %s%5d [%5.2f%%]", Current->GetName().c_str(), spacer, Current->GetUserCount(), percent);
3780                         totusers += Current->GetUserCount();
3781                         totservers++;
3782                         strlcpy(&matrix[line][depth],text,80);
3783                         line++;
3784                         for (unsigned int q = 0; q < Current->ChildCount(); q++)
3785                         {
3786                                 if ((HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str())))
3787                                 {
3788                                         if (*user->oper)
3789                                         {
3790                                                 ShowMap(Current->GetChild(q),user,(FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
3791                                         }
3792                                 }
3793                                 else
3794                                 {
3795                                         ShowMap(Current->GetChild(q),user,(FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
3796                                 }
3797                         }
3798                 }
3799         }
3800
3801         int HandleMotd(const char** parameters, int pcnt, userrec* user)
3802         {
3803                 if (pcnt > 0)
3804                 {
3805                         /* Remote MOTD, the server is within the 1st parameter */
3806                         std::deque<std::string> params;
3807                         params.push_back(parameters[0]);
3808
3809                         /* Send it out remotely, generate no reply yet */
3810                         TreeServer* s = FindServerMask(parameters[0]);
3811                         if (s)
3812                         {
3813                                 DoOneToOne(user->nick, "MOTD", params, s->GetName());
3814                         }
3815                         else
3816                         {
3817                                 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
3818                         }
3819                         return 1;
3820                 }
3821                 return 0;
3822         }
3823
3824         int HandleAdmin(const char** parameters, int pcnt, userrec* user)
3825         {
3826                 if (pcnt > 0)
3827                 {
3828                         /* Remote ADMIN, 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, "ADMIN", 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 HandleStats(const char** parameters, int pcnt, userrec* user)
3848         {
3849                 if (pcnt > 1)
3850                 {
3851                         /* Remote STATS, the server is within the 2nd parameter */
3852                         std::deque<std::string> params;
3853                         params.push_back(parameters[0]);
3854                         params.push_back(parameters[1]);
3855                         /* Send it out remotely, generate no reply yet */
3856                         TreeServer* s = FindServerMask(parameters[1]);
3857                         if (s)
3858                         {
3859                                 params[1] = s->GetName();
3860                                 DoOneToOne(user->nick, "STATS", params, s->GetName());
3861                         }
3862                         else
3863                         {
3864                                 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
3865                         }
3866                         return 1;
3867                 }
3868                 return 0;
3869         }
3870
3871         // Ok, prepare to be confused.
3872         // After much mulling over how to approach this, it struck me that
3873         // the 'usual' way of doing a /MAP isnt the best way. Instead of
3874         // keeping track of a ton of ascii characters, and line by line
3875         // under recursion working out where to place them using multiplications
3876         // and divisons, we instead render the map onto a backplane of characters
3877         // (a character matrix), then draw the branches as a series of "L" shapes
3878         // from the nodes. This is not only friendlier on CPU it uses less stack.
3879
3880         void HandleMap(const char** parameters, int pcnt, userrec* user)
3881         {
3882                 // This array represents a virtual screen which we will
3883                 // "scratch" draw to, as the console device of an irc
3884                 // client does not provide for a proper terminal.
3885                 float totusers = 0;
3886                 float totservers = 0;
3887                 char matrix[128][80];
3888                 for (unsigned int t = 0; t < 128; t++)
3889                 {
3890                         matrix[t][0] = '\0';
3891                 }
3892                 line = 0;
3893                 // The only recursive bit is called here.
3894                 ShowMap(TreeRoot,user,0,matrix,totusers,totservers);
3895                 // Process each line one by one. The algorithm has a limit of
3896                 // 128 servers (which is far more than a spanning tree should have
3897                 // anyway, so we're ok). This limit can be raised simply by making
3898                 // the character matrix deeper, 128 rows taking 10k of memory.
3899                 for (int l = 1; l < line; l++)
3900                 {
3901                         // scan across the line looking for the start of the
3902                         // servername (the recursive part of the algorithm has placed
3903                         // the servers at indented positions depending on what they
3904                         // are related to)
3905                         int first_nonspace = 0;
3906                         while (matrix[l][first_nonspace] == ' ')
3907                         {
3908                                 first_nonspace++;
3909                         }
3910                         first_nonspace--;
3911                         // Draw the `- (corner) section: this may be overwritten by
3912                         // another L shape passing along the same vertical pane, becoming
3913                         // a |- (branch) section instead.
3914                         matrix[l][first_nonspace] = '-';
3915                         matrix[l][first_nonspace-1] = '`';
3916                         int l2 = l - 1;
3917                         // Draw upwards until we hit the parent server, causing possibly
3918                         // other corners (`-) to become branches (|-)
3919                         while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
3920                         {
3921                                 matrix[l2][first_nonspace-1] = '|';
3922                                 l2--;
3923                         }
3924                 }
3925                 // dump the whole lot to the user. This is the easy bit, honest.
3926                 for (int t = 0; t < line; t++)
3927                 {
3928                         user->WriteServ("006 %s :%s",user->nick,&matrix[t][0]);
3929                 }
3930                 float avg_users = totusers / totservers;
3931                 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);
3932         user->WriteServ("007 %s :End of /MAP",user->nick);
3933                 return;
3934         }
3935
3936         int HandleSquit(const char** parameters, int pcnt, userrec* user)
3937         {
3938                 TreeServer* s = FindServerMask(parameters[0]);
3939                 if (s)
3940                 {
3941                         if (s == TreeRoot)
3942                         {
3943                                  user->WriteServ("NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
3944                                 return 1;
3945                         }
3946                         TreeSocket* sock = s->GetSocket();
3947                         if (sock)
3948                         {
3949                                 ServerInstance->Log(DEBUG,"Splitting server %s",s->GetName().c_str());
3950                                 ServerInstance->SNO->WriteToSnoMask('l',"SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
3951                                 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
3952                                 ServerInstance->SE->DelFd(sock);
3953                                 sock->Close();
3954                                 delete sock;
3955                         }
3956                         else
3957                         {
3958                                 user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
3959                         }
3960                 }
3961                 else
3962                 {
3963                          user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
3964                 }
3965                 return 1;
3966         }
3967
3968         int HandleTime(const char** parameters, int pcnt, userrec* user)
3969         {
3970                 if ((IS_LOCAL(user)) && (pcnt))
3971                 {
3972                         TreeServer* found = FindServerMask(parameters[0]);
3973                         if (found)
3974                         {
3975                                 // we dont' override for local server
3976                                 if (found == TreeRoot)
3977                                         return 0;
3978                                 
3979                                 std::deque<std::string> params;
3980                                 params.push_back(found->GetName());
3981                                 params.push_back(user->nick);
3982                                 DoOneToOne(ServerInstance->Config->ServerName,"TIME",params,found->GetName());
3983                         }
3984                         else
3985                         {
3986                                 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
3987                         }
3988                 }
3989                 return 1;
3990         }
3991
3992         int HandleRemoteWhois(const char** parameters, int pcnt, userrec* user)
3993         {
3994                 if ((IS_LOCAL(user)) && (pcnt > 1))
3995                 {
3996                         userrec* remote = ServerInstance->FindNick(parameters[1]);
3997                         if ((remote) && (remote->GetFd() < 0))
3998                         {
3999                                 std::deque<std::string> params;
4000                                 params.push_back(parameters[1]);
4001                                 DoOneToOne(user->nick,"IDLE",params,remote->server);
4002                                 return 1;
4003                         }
4004                         else if (!remote)
4005                         {
4006                                 user->WriteServ("401 %s %s :No such nick/channel",user->nick, parameters[1]);
4007                                 user->WriteServ("318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
4008                                 return 1;
4009                         }
4010                 }
4011                 return 0;
4012         }
4013
4014         void DoPingChecks(time_t curtime)
4015         {
4016                 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
4017                 {
4018                         TreeServer* serv = TreeRoot->GetChild(j);
4019                         TreeSocket* sock = serv->GetSocket();
4020                         if (sock)
4021                         {
4022                                 if (curtime >= serv->NextPingTime())
4023                                 {
4024                                         if (serv->AnsweredLastPing())
4025                                         {
4026                                                 sock->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" PING "+serv->GetName());
4027                                                 serv->SetNextPingTime(curtime + 60);
4028                                         }
4029                                         else
4030                                         {
4031                                                 // they didnt answer, boot them
4032                                                 ServerInstance->SNO->WriteToSnoMask('l',"Server \002%s\002 pinged out",serv->GetName().c_str());
4033                                                 sock->Squit(serv,"Ping timeout");
4034                                                 ServerInstance->SE->DelFd(sock);
4035                                                 sock->Close();
4036                                                 delete sock;
4037                                                 return;
4038                                         }
4039                                 }
4040                         }
4041                 }
4042         }
4043
4044         void ConnectServer(Link* x)
4045         {
4046                 insp_inaddr binip;
4047
4048                 /* Do we already have an IP? If so, no need to resolve it. */
4049                 if (insp_aton(x->IPAddr.c_str(), &binip) > 0)
4050                 {
4051                         TreeSocket* newsocket = new TreeSocket(ServerInstance, x->IPAddr,x->Port,false,10,x->Name.c_str());
4052                         if (newsocket->GetFd() > -1)
4053                         {
4054                                 /* Handled automatically on success */
4055                         }
4056                         else
4057                         {
4058                                 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
4059                                 delete newsocket;
4060                                 this->DoFailOver(x);
4061                         }
4062                 }
4063                 else
4064                 {
4065                         try
4066                         {
4067                                 ServernameResolver* snr = new ServernameResolver(ServerInstance,x->IPAddr, *x);
4068                                 ServerInstance->AddResolver(snr);
4069                         }
4070                         catch (ModuleException& e)
4071                         {
4072                                 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
4073                                 this->DoFailOver(x);
4074                         }
4075                 }
4076         }
4077
4078         void DoFailOver(Link* x)
4079         {
4080                 if (x->FailOver.length())
4081                 {
4082                         if (x->FailOver == x->Name)
4083                         {
4084                                 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());
4085                                 return;
4086                         }
4087                         Link* TryThisOne = this->FindLink(x->FailOver.c_str());
4088                         if (TryThisOne)
4089                         {
4090                                 ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Trying failover link for \002%s\002: \002%s\002...", x->Name.c_str(), TryThisOne->Name.c_str());
4091                                 ConnectServer(TryThisOne);
4092                         }
4093                         else
4094                         {
4095                                 ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Invalid failover server specified for server \002%s\002, will not follow!", x->Name.c_str());
4096                         }
4097                 }
4098         }
4099
4100         Link* FindLink(const std::string& name)
4101         {
4102                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
4103                 {
4104                         if (ServerInstance->MatchText(x->Name.c_str(), name.c_str()))
4105                         {
4106                                 return &(*x);
4107                         }
4108                 }
4109                 return NULL;
4110         }
4111
4112         void AutoConnectServers(time_t curtime)
4113         {
4114                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
4115                 {
4116                         if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
4117                         {
4118                                 ServerInstance->Log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
4119                                 x->NextConnectTime = curtime + x->AutoConnect;
4120                                 TreeServer* CheckDupe = FindServer(x->Name.c_str());
4121                                 if (x->FailOver.length())
4122                                 {
4123                                         TreeServer* CheckFailOver = FindServer(x->FailOver.c_str());
4124                                         if (CheckFailOver)
4125                                         {
4126                                                 /* The failover for this server is currently a member of the network.
4127                                                  * The failover probably succeeded, where the main link did not.
4128                                                  * Don't try the main link until the failover is gone again.
4129                                                  */
4130                                                 continue;
4131                                         }
4132                                 }
4133                                 if (!CheckDupe)
4134                                 {
4135                                         // an autoconnected server is not connected. Check if its time to connect it
4136                                         ServerInstance->SNO->WriteToSnoMask('l',"AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
4137                                         this->ConnectServer(&(*x));
4138                                 }
4139                         }
4140                 }
4141         }
4142
4143         int HandleVersion(const char** parameters, int pcnt, userrec* user)
4144         {
4145                 // we've already checked if pcnt > 0, so this is safe
4146                 TreeServer* found = FindServerMask(parameters[0]);
4147                 if (found)
4148                 {
4149                         std::string Version = found->GetVersion();
4150                         user->WriteServ("351 %s :%s",user->nick,Version.c_str());
4151                         if (found == TreeRoot)
4152                         {
4153                                 std::stringstream out(ServerInstance->Config->data005);
4154                                 std::string token = "";
4155                                 std::string line5 = "";
4156                                 int token_counter = 0;
4157
4158                                 while (!out.eof())
4159                                 {
4160                                         out >> token;
4161                                         line5 = line5 + token + " ";   
4162                                         token_counter++;
4163
4164                                         if ((token_counter >= 13) || (out.eof() == true))
4165                                         {
4166                                                 user->WriteServ("005 %s %s:are supported by this server",user->nick,line5.c_str());
4167                                                 line5 = "";
4168                                                 token_counter = 0;
4169                                         }
4170                                 }
4171                         }
4172                 }
4173                 else
4174                 {
4175                         user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
4176                 }
4177                 return 1;
4178         }
4179         
4180         int HandleConnect(const char** parameters, int pcnt, userrec* user)
4181         {
4182                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
4183                 {
4184                         if (ServerInstance->MatchText(x->Name.c_str(),parameters[0]))
4185                         {
4186                                 TreeServer* CheckDupe = FindServer(x->Name.c_str());
4187                                 if (!CheckDupe)
4188                                 {
4189                                         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);
4190                                         ConnectServer(&(*x));
4191                                         return 1;
4192                                 }
4193                                 else
4194                                 {
4195                                         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());
4196                                         return 1;
4197                                 }
4198                         }
4199                 }
4200                 user->WriteServ("NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
4201                 return 1;
4202         }
4203
4204         virtual int OnStats(char statschar, userrec* user, string_list &results)
4205         {
4206                 if (statschar == 'c')
4207                 {
4208                         for (unsigned int i = 0; i < LinkBlocks.size(); i++)
4209                         {
4210                                 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');
4211                                 results.push_back(std::string(ServerInstance->Config->ServerName)+" 244 "+user->nick+" H * * "+LinkBlocks[i].Name.c_str());
4212                         }
4213                         results.push_back(std::string(ServerInstance->Config->ServerName)+" 219 "+user->nick+" "+statschar+" :End of /STATS report");
4214                         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);
4215                         return 1;
4216                 }
4217                 return 0;
4218         }
4219
4220         virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated)
4221         {
4222                 /* If the command doesnt appear to be valid, we dont want to mess with it. */
4223                 if (!validated)
4224                         return 0;
4225
4226                 if (command == "CONNECT")
4227                 {
4228                         return this->HandleConnect(parameters,pcnt,user);
4229                 }
4230                 else if (command == "STATS")
4231                 {
4232                         return this->HandleStats(parameters,pcnt,user);
4233                 }
4234                 else if (command == "MOTD")
4235                 {
4236                         return this->HandleMotd(parameters,pcnt,user);
4237                 }
4238                 else if (command == "ADMIN")
4239                 {
4240                         return this->HandleAdmin(parameters,pcnt,user);
4241                 }
4242                 else if (command == "SQUIT")
4243                 {
4244                         return this->HandleSquit(parameters,pcnt,user);
4245                 }
4246                 else if (command == "MAP")
4247                 {
4248                         this->HandleMap(parameters,pcnt,user);
4249                         return 1;
4250                 }
4251                 else if ((command == "TIME") && (pcnt > 0))
4252                 {
4253                         return this->HandleTime(parameters,pcnt,user);
4254                 }
4255                 else if (command == "LUSERS")
4256                 {
4257                         this->HandleLusers(parameters,pcnt,user);
4258                         return 1;
4259                 }
4260                 else if (command == "LINKS")
4261                 {
4262                         this->HandleLinks(parameters,pcnt,user);
4263                         return 1;
4264                 }
4265                 else if (command == "WHOIS")
4266                 {
4267                         if (pcnt > 1)
4268                         {
4269                                 // remote whois
4270                                 return this->HandleRemoteWhois(parameters,pcnt,user);
4271                         }
4272                 }
4273                 else if ((command == "VERSION") && (pcnt > 0))
4274                 {
4275                         this->HandleVersion(parameters,pcnt,user);
4276                         return 1;
4277                 }
4278                 else if (ServerInstance->IsValidModuleCommand(command, pcnt, user))
4279                 {
4280                         // this bit of code cleverly routes all module commands
4281                         // to all remote severs *automatically* so that modules
4282                         // can just handle commands locally, without having
4283                         // to have any special provision in place for remote
4284                         // commands and linking protocols.
4285                         std::deque<std::string> params;
4286                         params.clear();
4287                         for (int j = 0; j < pcnt; j++)
4288                         {
4289                                 if (strchr(parameters[j],' '))
4290                                 {
4291                                         params.push_back(":" + std::string(parameters[j]));
4292                                 }
4293                                 else
4294                                 {
4295                                         params.push_back(std::string(parameters[j]));
4296                                 }
4297                         }
4298                         ServerInstance->Log(DEBUG,"Globally route '%s'",command.c_str());
4299                         DoOneToMany(user->nick,command,params);
4300                 }
4301                 return 0;
4302         }
4303
4304         virtual void OnGetServerDescription(const std::string &servername,std::string &description)
4305         {
4306                 TreeServer* s = FindServer(servername);
4307                 if (s)
4308                 {
4309                         description = s->GetDesc();
4310                 }
4311         }
4312
4313         virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
4314         {
4315                 if (IS_LOCAL(source))
4316                 {
4317                         std::deque<std::string> params;
4318                         params.push_back(dest->nick);
4319                         params.push_back(channel->name);
4320                         DoOneToMany(source->nick,"INVITE",params);
4321                 }
4322         }
4323
4324         virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, const std::string &topic)
4325         {
4326                 std::deque<std::string> params;
4327                 params.push_back(chan->name);
4328                 params.push_back(":"+topic);
4329                 DoOneToMany(user->nick,"TOPIC",params);
4330         }
4331
4332         virtual void OnWallops(userrec* user, const std::string &text)
4333         {
4334                 if (IS_LOCAL(user))
4335                 {
4336                         std::deque<std::string> params;
4337                         params.push_back(":"+text);
4338                         DoOneToMany(user->nick,"WALLOPS",params);
4339                 }
4340         }
4341
4342         virtual void OnUserNotice(userrec* user, void* dest, int target_type, const std::string &text, char status)
4343         {
4344                 if (target_type == TYPE_USER)
4345                 {
4346                         userrec* d = (userrec*)dest;
4347                         if ((d->GetFd() < 0) && (IS_LOCAL(user)))
4348                         {
4349                                 std::deque<std::string> params;
4350                                 params.clear();
4351                                 params.push_back(d->nick);
4352                                 params.push_back(":"+text);
4353                                 DoOneToOne(user->nick,"NOTICE",params,d->server);
4354                         }
4355                 }
4356                 else if (target_type == TYPE_CHANNEL)
4357                 {
4358                         if (IS_LOCAL(user))
4359                         {
4360                                 chanrec *c = (chanrec*)dest;
4361                                 if (c)
4362                                 {
4363                                         std::string cname = c->name;
4364                                         if (status)
4365                                                 cname = status + cname;
4366                                         std::deque<TreeServer*> list;
4367                                         GetListOfServersForChannel(c,list);
4368                                         unsigned int ucount = list.size();
4369                                         for (unsigned int i = 0; i < ucount; i++)
4370                                         {
4371                                                 TreeSocket* Sock = list[i]->GetSocket();
4372                                                 if (Sock)
4373                                                         Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+cname+" :"+text);
4374                                         }
4375                                 }
4376                         }
4377                 }
4378                 else if (target_type == TYPE_SERVER)
4379                 {
4380                         if (IS_LOCAL(user))
4381                         {
4382                                 char* target = (char*)dest;
4383                                 std::deque<std::string> par;
4384                                 par.push_back(target);
4385                                 par.push_back(":"+text);
4386                                 DoOneToMany(user->nick,"NOTICE",par);
4387                         }
4388                 }
4389         }
4390
4391         virtual void OnUserMessage(userrec* user, void* dest, int target_type, const std::string &text, char status)
4392         {
4393                 if (target_type == TYPE_USER)
4394                 {
4395                         // route private messages which are targetted at clients only to the server
4396                         // which needs to receive them
4397                         userrec* d = (userrec*)dest;
4398                         if ((d->GetFd() < 0) && (IS_LOCAL(user)))
4399                         {
4400                                 std::deque<std::string> params;
4401                                 params.clear();
4402                                 params.push_back(d->nick);
4403                                 params.push_back(":"+text);
4404                                 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
4405                         }
4406                 }
4407                 else if (target_type == TYPE_CHANNEL)
4408                 {
4409                         if (IS_LOCAL(user))
4410                         {
4411                                 chanrec *c = (chanrec*)dest;
4412                                 if (c)
4413                                 {
4414                                         std::string cname = c->name;
4415                                         if (status)
4416                                                 cname = status + cname;
4417                                         std::deque<TreeServer*> list;
4418                                         GetListOfServersForChannel(c,list);
4419                                         unsigned int ucount = list.size();
4420                                         for (unsigned int i = 0; i < ucount; i++)
4421                                         {
4422                                                 TreeSocket* Sock = list[i]->GetSocket();
4423                                                 if (Sock)
4424                                                         Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+cname+" :"+text);
4425                                         }
4426                                 }
4427                         }
4428                 }
4429                 else if (target_type == TYPE_SERVER)
4430                 {
4431                         if (IS_LOCAL(user))
4432                         {
4433                                 char* target = (char*)dest;
4434                                 std::deque<std::string> par;
4435                                 par.push_back(target);
4436                                 par.push_back(":"+text);
4437                                 DoOneToMany(user->nick,"PRIVMSG",par);
4438                         }
4439                 }
4440         }
4441
4442         virtual void OnBackgroundTimer(time_t curtime)
4443         {
4444                 AutoConnectServers(curtime);
4445                 DoPingChecks(curtime);
4446         }
4447
4448         virtual void OnUserJoin(userrec* user, chanrec* channel)
4449         {
4450                 // Only do this for local users
4451                 if (IS_LOCAL(user))
4452                 {
4453                         char ts[24];
4454                         snprintf(ts,24,"%lu",(unsigned long)channel->age);
4455
4456                         std::deque<std::string> params;
4457                         params.clear();
4458                         params.push_back(channel->name);
4459
4460                         /** XXX: The client protocol will IGNORE this parameter.
4461                          * We could make use of it if we wanted to keep the TS
4462                          * in step if somehow we lose it.
4463                          */
4464                         params.push_back(ts);
4465
4466                         if (channel->GetUserCounter() > 1)
4467                         {
4468                                 // not the first in the channel
4469                                 DoOneToMany(user->nick,"JOIN",params);
4470                         }
4471                         else
4472                         {
4473                                 // first in the channel, set up their permissions
4474                                 // and the channel TS with FJOIN.
4475                                 params.clear();
4476                                 params.push_back(channel->name);
4477                                 params.push_back(ts);
4478                                 params.push_back("@,"+std::string(user->nick));
4479                                 DoOneToMany(ServerInstance->Config->ServerName,"FJOIN",params);
4480                         }
4481                 }
4482         }
4483
4484         virtual void OnChangeHost(userrec* user, const std::string &newhost)
4485         {
4486                 // only occurs for local clients
4487                 if (user->registered != REG_ALL)
4488                         return;
4489                 std::deque<std::string> params;
4490                 params.push_back(newhost);
4491                 DoOneToMany(user->nick,"FHOST",params);
4492         }
4493
4494         virtual void OnChangeName(userrec* user, const std::string &gecos)
4495         {
4496                 // only occurs for local clients
4497                 if (user->registered != REG_ALL)
4498                         return;
4499                 std::deque<std::string> params;
4500                 params.push_back(gecos);
4501                 DoOneToMany(user->nick,"FNAME",params);
4502         }
4503
4504         virtual void OnUserPart(userrec* user, chanrec* channel, const std::string &partmessage)
4505         {
4506                 if (IS_LOCAL(user))
4507                 {
4508                         std::deque<std::string> params;
4509                         params.push_back(channel->name);
4510                         if (partmessage != "")
4511                                 params.push_back(":"+partmessage);
4512                         DoOneToMany(user->nick,"PART",params);
4513                 }
4514         }
4515
4516         virtual void OnUserConnect(userrec* user)
4517         {
4518                 char agestr[MAXBUF];
4519                 if (IS_LOCAL(user))
4520                 {
4521                         std::deque<std::string> params;
4522                         snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
4523                         params.push_back(agestr);
4524                         params.push_back(user->nick);
4525                         params.push_back(user->host);
4526                         params.push_back(user->dhost);
4527                         params.push_back(user->ident);
4528                         params.push_back("+"+std::string(user->FormatModes()));
4529                         params.push_back(user->GetIPString());
4530                         params.push_back(":"+std::string(user->fullname));
4531                         DoOneToMany(ServerInstance->Config->ServerName,"NICK",params);
4532
4533                         // User is Local, change needs to be reflected!
4534                         TreeServer* SourceServer = FindServer(user->server);
4535                         if (SourceServer)
4536                         {
4537                                 SourceServer->AddUserCount();
4538                         }
4539
4540                 }
4541         }
4542
4543         virtual void OnUserQuit(userrec* user, const std::string &reason)
4544         {
4545                 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
4546                 {
4547                         std::deque<std::string> params;
4548                         params.push_back(":"+reason);
4549                         DoOneToMany(user->nick,"QUIT",params);
4550                 }
4551                 // Regardless, We need to modify the user Counts..
4552                 TreeServer* SourceServer = FindServer(user->server);
4553                 if (SourceServer)
4554                 {
4555                         SourceServer->DelUserCount();
4556                 }
4557
4558         }
4559
4560         virtual void OnUserPostNick(userrec* user, const std::string &oldnick)
4561         {
4562                 if (IS_LOCAL(user))
4563                 {
4564                         std::deque<std::string> params;
4565                         params.push_back(user->nick);
4566                         DoOneToMany(oldnick,"NICK",params);
4567                 }
4568         }
4569
4570         virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, const std::string &reason)
4571         {
4572                 if ((source) && (IS_LOCAL(source)))
4573                 {
4574                         std::deque<std::string> params;
4575                         params.push_back(chan->name);
4576                         params.push_back(user->nick);
4577                         params.push_back(":"+reason);
4578                         DoOneToMany(source->nick,"KICK",params);
4579                 }
4580                 else if (!source)
4581                 {
4582                         std::deque<std::string> params;
4583                         params.push_back(chan->name);
4584                         params.push_back(user->nick);
4585                         params.push_back(":"+reason);
4586                         DoOneToMany(ServerInstance->Config->ServerName,"KICK",params);
4587                 }
4588         }
4589
4590         virtual void OnRemoteKill(userrec* source, userrec* dest, const std::string &reason)
4591         {
4592                 std::deque<std::string> params;
4593                 params.push_back(dest->nick);
4594                 params.push_back(":"+reason);
4595                 DoOneToMany(source->nick,"KILL",params);
4596         }
4597
4598         virtual void OnRehash(const std::string &parameter)
4599         {
4600                 if (parameter != "")
4601                 {
4602                         std::deque<std::string> params;
4603                         params.push_back(parameter);
4604                         DoOneToMany(ServerInstance->Config->ServerName,"REHASH",params);
4605                         // check for self
4606                         if (ServerInstance->MatchText(ServerInstance->Config->ServerName,parameter))
4607                         {
4608                                 ServerInstance->WriteOpers("*** Remote rehash initiated from server \002%s\002",ServerInstance->Config->ServerName);
4609                                 ServerInstance->RehashServer();
4610                         }
4611                 }
4612                 ReadConfiguration(false);
4613         }
4614
4615         // note: the protocol does not allow direct umode +o except
4616         // via NICK with 8 params. sending OPERTYPE infers +o modechange
4617         // locally.
4618         virtual void OnOper(userrec* user, const std::string &opertype)
4619         {
4620                 if (IS_LOCAL(user))
4621                 {
4622                         std::deque<std::string> params;
4623                         params.push_back(opertype);
4624                         DoOneToMany(user->nick,"OPERTYPE",params);
4625                 }
4626         }
4627
4628         void OnLine(userrec* source, const std::string &host, bool adding, char linetype, long duration, const std::string &reason)
4629         {
4630                 if (IS_LOCAL(source))
4631                 {
4632                         char type[8];
4633                         snprintf(type,8,"%cLINE",linetype);
4634                         std::string stype = type;
4635                         if (adding)
4636                         {
4637                                 char sduration[MAXBUF];
4638                                 snprintf(sduration,MAXBUF,"%ld",duration);
4639                                 std::deque<std::string> params;
4640                                 params.push_back(host);
4641                                 params.push_back(sduration);
4642                                 params.push_back(":"+reason);
4643                                 DoOneToMany(source->nick,stype,params);
4644                         }
4645                         else
4646                         {
4647                                 std::deque<std::string> params;
4648                                 params.push_back(host);
4649                                 DoOneToMany(source->nick,stype,params);
4650                         }
4651                 }
4652         }
4653
4654         virtual void OnAddGLine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
4655         {
4656                 OnLine(source,hostmask,true,'G',duration,reason);
4657         }
4658         
4659         virtual void OnAddZLine(long duration, userrec* source, const std::string &reason, const std::string &ipmask)
4660         {
4661                 OnLine(source,ipmask,true,'Z',duration,reason);
4662         }
4663
4664         virtual void OnAddQLine(long duration, userrec* source, const std::string &reason, const std::string &nickmask)
4665         {
4666                 OnLine(source,nickmask,true,'Q',duration,reason);
4667         }
4668
4669         virtual void OnAddELine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
4670         {
4671                 OnLine(source,hostmask,true,'E',duration,reason);
4672         }
4673
4674         virtual void OnDelGLine(userrec* source, const std::string &hostmask)
4675         {
4676                 OnLine(source,hostmask,false,'G',0,"");
4677         }
4678
4679         virtual void OnDelZLine(userrec* source, const std::string &ipmask)
4680         {
4681                 OnLine(source,ipmask,false,'Z',0,"");
4682         }
4683
4684         virtual void OnDelQLine(userrec* source, const std::string &nickmask)
4685         {
4686                 OnLine(source,nickmask,false,'Q',0,"");
4687         }
4688
4689         virtual void OnDelELine(userrec* source, const std::string &hostmask)
4690         {
4691                 OnLine(source,hostmask,false,'E',0,"");
4692         }
4693
4694         virtual void OnMode(userrec* user, void* dest, int target_type, const std::string &text)
4695         {
4696                 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
4697                 {
4698                         if (target_type == TYPE_USER)
4699                         {
4700                                 userrec* u = (userrec*)dest;
4701                                 std::deque<std::string> params;
4702                                 params.push_back(u->nick);
4703                                 params.push_back(text);
4704                                 DoOneToMany(user->nick,"MODE",params);
4705                         }
4706                         else
4707                         {
4708                                 chanrec* c = (chanrec*)dest;
4709                                 std::deque<std::string> params;
4710                                 params.push_back(c->name);
4711                                 params.push_back(text);
4712                                 DoOneToMany(user->nick,"MODE",params);
4713                         }
4714                 }
4715         }
4716
4717         virtual void OnSetAway(userrec* user)
4718         {
4719                 if (IS_LOCAL(user))
4720                 {
4721                         std::deque<std::string> params;
4722                         params.push_back(":"+std::string(user->awaymsg));
4723                         DoOneToMany(user->nick,"AWAY",params);
4724                 }
4725         }
4726
4727         virtual void OnCancelAway(userrec* user)
4728         {
4729                 if (IS_LOCAL(user))
4730                 {
4731                         std::deque<std::string> params;
4732                         params.clear();
4733                         DoOneToMany(user->nick,"AWAY",params);
4734                 }
4735         }
4736
4737         virtual void ProtoSendMode(void* opaque, int target_type, void* target, const std::string &modeline)
4738         {
4739                 TreeSocket* s = (TreeSocket*)opaque;
4740                 if (target)
4741                 {
4742                         if (target_type == TYPE_USER)
4743                         {
4744                                 userrec* u = (userrec*)target;
4745                                 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+u->nick+" "+ConvToStr(u->age)+" "+modeline);
4746                         }
4747                         else
4748                         {
4749                                 chanrec* c = (chanrec*)target;
4750                                 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age)+" "+modeline);
4751                         }
4752                 }
4753         }
4754
4755         virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, const std::string &extname, const std::string &extdata)
4756         {
4757                 TreeSocket* s = (TreeSocket*)opaque;
4758                 if (target)
4759                 {
4760                         if (target_type == TYPE_USER)
4761                         {
4762                                 userrec* u = (userrec*)target;
4763                                 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+u->nick+" "+extname+" :"+extdata);
4764                         }
4765                         else if (target_type == TYPE_OTHER)
4766                         {
4767                                 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA * "+extname+" :"+extdata);
4768                         }
4769                         else if (target_type == TYPE_CHANNEL)
4770                         {
4771                                 chanrec* c = (chanrec*)target;
4772                                 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+c->name+" "+extname+" :"+extdata);
4773                         }
4774                 }
4775         }
4776
4777         virtual void OnEvent(Event* event)
4778         {
4779                 if (event->GetEventID() == "send_metadata")
4780                 {
4781                         std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
4782                         if (params->size() < 3)
4783                                 return;
4784                         (*params)[2] = ":" + (*params)[2];
4785                         DoOneToMany(ServerInstance->Config->ServerName,"METADATA",*params);
4786                 }
4787                 else if (event->GetEventID() == "send_mode")
4788                 {
4789                         std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
4790                         if (params->size() < 2)
4791                                 return;
4792                         // Insert the TS value of the object, either userrec or chanrec
4793                         time_t ourTS = 0;
4794                         userrec* a = ServerInstance->FindNick((*params)[0]);
4795                         if (a)
4796                         {
4797                                 ourTS = a->age;
4798                         }
4799                         else
4800                         {
4801                                 chanrec* a = ServerInstance->FindChan((*params)[0]);
4802                                 if (a)
4803                                 {
4804                                         ourTS = a->age;
4805                                 }
4806                         }
4807                         params->insert(params->begin() + 1,ConvToStr(ourTS));
4808                         DoOneToMany(ServerInstance->Config->ServerName,"FMODE",*params);
4809                 }
4810         }
4811
4812         virtual ~ModuleSpanningTree()
4813         {
4814         }
4815
4816         virtual Version GetVersion()
4817         {
4818                 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
4819         }
4820
4821         void Implements(char* List)
4822         {
4823                 List[I_OnPreCommand] = List[I_OnGetServerDescription] = List[I_OnUserInvite] = List[I_OnPostLocalTopicChange] = 1;
4824                 List[I_OnWallops] = List[I_OnUserNotice] = List[I_OnUserMessage] = List[I_OnBackgroundTimer] = 1;
4825                 List[I_OnUserJoin] = List[I_OnChangeHost] = List[I_OnChangeName] = List[I_OnUserPart] = List[I_OnUserConnect] = 1;
4826                 List[I_OnUserQuit] = List[I_OnUserPostNick] = List[I_OnUserKick] = List[I_OnRemoteKill] = List[I_OnRehash] = 1;
4827                 List[I_OnOper] = List[I_OnAddGLine] = List[I_OnAddZLine] = List[I_OnAddQLine] = List[I_OnAddELine] = 1;
4828                 List[I_OnDelGLine] = List[I_OnDelZLine] = List[I_OnDelQLine] = List[I_OnDelELine] = List[I_ProtoSendMode] = List[I_OnMode] = 1;
4829                 List[I_OnStats] = List[I_ProtoSendMetaData] = List[I_OnEvent] = List[I_OnSetAway] = List[I_OnCancelAway] = 1;
4830         }
4831
4832         /* It is IMPORTANT that m_spanningtree is the last module in the chain
4833          * so that any activity it sees is FINAL, e.g. we arent going to send out
4834          * a NICK message before m_cloaking has finished putting the +x on the user,
4835          * etc etc.
4836          * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
4837          * the module call queue.
4838          */
4839         Priority Prioritize()
4840         {
4841                 return PRIORITY_LAST;
4842         }
4843 };
4844
4845 void DoFailOver(Link* x)
4846 {
4847         TreeProtocolModule->DoFailOver(x);
4848 }
4849
4850 Link* FindLink(const std::string& name)
4851 {
4852         return TreeProtocolModule->FindLink(name);
4853 }
4854
4855 class ModuleSpanningTreeFactory : public ModuleFactory
4856 {
4857  public:
4858         ModuleSpanningTreeFactory()
4859         {
4860         }
4861         
4862         ~ModuleSpanningTreeFactory()
4863         {
4864         }
4865         
4866         virtual Module * CreateModule(InspIRCd* Me)
4867         {
4868                 TreeProtocolModule = new ModuleSpanningTree(Me);
4869                 return TreeProtocolModule;
4870         }
4871         
4872 };
4873
4874
4875 extern "C" void * init_module( void )
4876 {
4877         return new ModuleSpanningTreeFactory;
4878 }