]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree.cpp
7a71df21ae224529c3c63771d90d7ad07729f947
[user/henk/code/inspircd.git] / src / modules / m_spanningtree.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  Inspire is copyright (C) 2002-2005 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 <stdio.h>
22 #include <vector>
23 #include <deque>
24 #include "globals.h"
25 #include "inspircd_config.h"
26 #ifdef GCC3
27 #include <ext/hash_map>
28 #else
29 #include <hash_map>
30 #endif
31 #include "users.h"
32 #include "channels.h"
33 #include "modules.h"
34 #include "commands.h"
35 #include "socket.h"
36 #include "helperfuncs.h"
37 #include "inspircd.h"
38 #include "inspstring.h"
39 #include "hashcomp.h"
40 #include "message.h"
41 #include "xline.h"
42 #include "typedefs.h"
43 #include "cull_list.h"
44 #include "aes.h"
45
46 #ifdef GCC3
47 #define nspace __gnu_cxx
48 #else
49 #define nspace std
50 #endif
51
52 /*
53  * The server list in InspIRCd is maintained as two structures
54  * which hold the data in different ways. Most of the time, we
55  * want to very quicky obtain three pieces of information:
56  *
57  * (1) The information on a server
58  * (2) The information on the server we must send data through
59  *     to actually REACH the server we're after
60  * (3) Potentially, the child/parent objects of this server
61  *
62  * The InspIRCd spanning protocol provides easy access to these
63  * by storing the data firstly in a recursive structure, where
64  * each item references its parent item, and a dynamic list
65  * of child items, and another structure which stores the items
66  * hashed, linearly. This means that if we want to find a server
67  * by name quickly, we can look it up in the hash, avoiding
68  * any O(n) lookups. If however, during a split or sync, we want
69  * to apply an operation to a server, and any of its child objects
70  * we can resort to recursion to walk the tree structure.
71  */
72
73 class ModuleSpanningTree;
74 static ModuleSpanningTree* TreeProtocolModule;
75
76 extern std::vector<Module*> modules;
77 extern std::vector<ircd_module*> factory;
78 extern int MODCOUNT;
79
80 /* Any socket can have one of five states at any one time.
81  * The LISTENER state indicates a socket which is listening
82  * for connections. It cannot receive data itself, only incoming
83  * sockets.
84  * The CONNECTING state indicates an outbound socket which is
85  * waiting to be writeable.
86  * The WAIT_AUTH_1 state indicates the socket is outbound and
87  * has successfully connected, but has not yet sent and received
88  * SERVER strings.
89  * The WAIT_AUTH_2 state indicates that the socket is inbound
90  * (allocated by a LISTENER) but has not yet sent and received
91  * SERVER strings.
92  * The CONNECTED state represents a fully authorized, fully
93  * connected server.
94  */
95 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
96
97 /* We need to import these from the core for use in netbursts */
98 extern user_hash clientlist;
99 extern chan_hash chanlist;
100
101 /* Foward declarations */
102 class TreeServer;
103 class TreeSocket;
104
105 /* This variable represents the root of the server tree
106  * (for all intents and purposes, it's us)
107  */
108 TreeServer *TreeRoot;
109
110 Server* Srv;
111
112 /* This hash_map holds the hash equivalent of the server
113  * tree, used for rapid linear lookups.
114  */
115 typedef nspace::hash_map<std::string, TreeServer*> server_hash;
116 server_hash serverlist;
117
118 /* More forward declarations */
119 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> &params, std::string target);
120 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> &params, std::string omit);
121 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> &params);
122 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, std::string command, std::deque<std::string> &params);
123 void ReadConfiguration(bool rebind);
124
125 /* Imported from xline.cpp for use during netburst */
126 extern std::vector<KLine> klines;
127 extern std::vector<GLine> glines;
128 extern std::vector<ZLine> zlines;
129 extern std::vector<QLine> qlines;
130 extern std::vector<ELine> elines;
131 extern std::vector<KLine> pklines;
132 extern std::vector<GLine> pglines;
133 extern std::vector<ZLine> pzlines;
134 extern std::vector<QLine> pqlines;
135 extern std::vector<ELine> pelines;
136
137 /* Each server in the tree is represented by one class of
138  * type TreeServer. A locally connected TreeServer can
139  * have a class of type TreeSocket associated with it, for
140  * remote servers, the TreeSocket entry will be NULL.
141  * Each server also maintains a pointer to its parent
142  * (NULL if this server is ours, at the top of the tree)
143  * and a pointer to its "Route" (see the comments in the
144  * constructors below), and also a dynamic list of pointers
145  * to its children which can be iterated recursively
146  * if required. Creating or deleting objects of type
147  * TreeServer automatically maintains the hash_map of
148  * TreeServer items, deleting and inserting them as they
149  * are created and destroyed.
150  */
151
152 class TreeServer
153 {
154         TreeServer* Parent;                     /* Parent entry */
155         TreeServer* Route;                      /* Route entry */
156         std::vector<TreeServer*> Children;      /* List of child objects */
157         std::string ServerName;                 /* Server's name */
158         std::string ServerDesc;                 /* Server's description */
159         std::string VersionString;              /* Version string or empty string */
160         int UserCount;                          /* Not used in this version */
161         int OperCount;                          /* Not used in this version */
162         TreeSocket* Socket;                     /* For directly connected servers this points at the socket object */
163         time_t NextPing;                        /* After this time, the server should be PINGed*/
164         bool LastPingWasGood;                   /* True if the server responded to the last PING with a PONG */
165         
166  public:
167
168         /* We don't use this constructor. Its a dummy, and won't cause any insertion
169          * of the TreeServer into the hash_map. See below for the two we DO use.
170          */
171         TreeServer()
172         {
173                 Parent = NULL;
174                 ServerName = "";
175                 ServerDesc = "";
176                 VersionString = "";
177                 UserCount = OperCount = 0;
178                 VersionString = Srv->GetVersion();
179         }
180
181         /* We use this constructor only to create the 'root' item, TreeRoot, which
182          * represents our own server. Therefore, it has no route, no parent, and
183          * no socket associated with it. Its version string is our own local version.
184          */
185         TreeServer(std::string Name, std::string Desc) : ServerName(Name), ServerDesc(Desc)
186         {
187                 Parent = NULL;
188                 VersionString = "";
189                 UserCount = OperCount = 0;
190                 VersionString = Srv->GetVersion();
191                 Route = NULL;
192                 Socket = NULL; /* Fix by brain */
193                 AddHashEntry();
194         }
195
196         /* When we create a new server, we call this constructor to initialize it.
197          * This constructor initializes the server's Route and Parent, and sets up
198          * its ping counters so that it will be pinged one minute from now.
199          */
200         TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name), ServerDesc(Desc), Socket(Sock)
201         {
202                 VersionString = "";
203                 UserCount = OperCount = 0;
204                 this->SetNextPingTime(time(NULL) + 60);
205                 this->SetPingFlag();
206
207                 /* find the 'route' for this server (e.g. the one directly connected
208                  * to the local server, which we can use to reach it)
209                  *
210                  * In the following example, consider we have just added a TreeServer
211                  * class for server G on our network, of which we are server A.
212                  * To route traffic to G (marked with a *) we must send the data to
213                  * B (marked with a +) so this algorithm initializes the 'Route'
214                  * value to point at whichever server traffic must be routed through
215                  * to get here. If we were to try this algorithm with server B,
216                  * the Route pointer would point at its own object ('this').
217                  *
218                  *              A
219                  *             / \
220                  *          + B   C
221                  *           / \   \
222                  *          D   E   F
223                  *         /         \
224                  *      * G           H
225                  *
226                  * We only run this algorithm when a server is created, as
227                  * the routes remain constant while ever the server exists, and
228                  * do not need to be re-calculated.
229                  */
230
231                 Route = Above;
232                 if (Route == TreeRoot)
233                 {
234                         Route = this;
235                 }
236                 else
237                 {
238                         while (this->Route->GetParent() != TreeRoot)
239                         {
240                                 this->Route = Route->GetParent();
241                         }
242                 }
243
244                 /* Because recursive code is slow and takes a lot of resources,
245                  * we store two representations of the server tree. The first
246                  * is a recursive structure where each server references its
247                  * children and its parent, which is used for netbursts and
248                  * netsplits to dump the whole dataset to the other server,
249                  * and the second is used for very fast lookups when routing
250                  * messages and is instead a hash_map, where each item can
251                  * be referenced by its server name. The AddHashEntry()
252                  * call below automatically inserts each TreeServer class
253                  * into the hash_map as it is created. There is a similar
254                  * maintainance call in the destructor to tidy up deleted
255                  * servers.
256                  */
257
258                 this->AddHashEntry();
259         }
260
261         /* This method is used to add the structure to the
262          * hash_map for linear searches. It is only called
263          * by the constructors.
264          */
265         void AddHashEntry()
266         {
267                 server_hash::iterator iter;
268                 iter = serverlist.find(this->ServerName);
269                 if (iter == serverlist.end())
270                         serverlist[this->ServerName] = this;
271         }
272
273         /* This method removes the reference to this object
274          * from the hash_map which is used for linear searches.
275          * It is only called by the default destructor.
276          */
277         void DelHashEntry()
278         {
279                 server_hash::iterator iter;
280                 iter = serverlist.find(this->ServerName);
281                 if (iter != serverlist.end())
282                         serverlist.erase(iter);
283         }
284
285         /* These accessors etc should be pretty self-
286          * explanitory.
287          */
288
289         TreeServer* GetRoute()
290         {
291                 return Route;
292         }
293
294         std::string GetName()
295         {
296                 return ServerName;
297         }
298
299         std::string GetDesc()
300         {
301                 return ServerDesc;
302         }
303
304         std::string GetVersion()
305         {
306                 return VersionString;
307         }
308
309         void SetNextPingTime(time_t t)
310         {
311                 this->NextPing = t;
312                 LastPingWasGood = false;
313         }
314
315         time_t NextPingTime()
316         {
317                 return NextPing;
318         }
319
320         bool AnsweredLastPing()
321         {
322                 return LastPingWasGood;
323         }
324
325         void SetPingFlag()
326         {
327                 LastPingWasGood = true;
328         }
329
330         int GetUserCount()
331         {
332                 return UserCount;
333         }
334
335         int GetOperCount()
336         {
337                 return OperCount;
338         }
339
340         TreeSocket* GetSocket()
341         {
342                 return Socket;
343         }
344
345         TreeServer* GetParent()
346         {
347                 return Parent;
348         }
349
350         void SetVersion(std::string Version)
351         {
352                 VersionString = Version;
353         }
354
355         unsigned int ChildCount()
356         {
357                 return Children.size();
358         }
359
360         TreeServer* GetChild(unsigned int n)
361         {
362                 if (n < Children.size())
363                 {
364                         /* Make sure they  cant request
365                          * an out-of-range object. After
366                          * all we know what these programmer
367                          * types are like *grin*.
368                          */
369                         return Children[n];
370                 }
371                 else
372                 {
373                         return NULL;
374                 }
375         }
376
377         void AddChild(TreeServer* Child)
378         {
379                 Children.push_back(Child);
380         }
381
382         bool DelChild(TreeServer* Child)
383         {
384                 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
385                 {
386                         if (*a == Child)
387                         {
388                                 Children.erase(a);
389                                 return true;
390                         }
391                 }
392                 return false;
393         }
394
395         /* Removes child nodes of this node, and of that node, etc etc.
396          * This is used during netsplits to automatically tidy up the
397          * server tree. It is slow, we don't use it for much else.
398          */
399         bool Tidy()
400         {
401                 bool stillchildren = true;
402                 while (stillchildren)
403                 {
404                         stillchildren = false;
405                         for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
406                         {
407                                 TreeServer* s = (TreeServer*)*a;
408                                 s->Tidy();
409                                 Children.erase(a);
410                                 delete s;
411                                 stillchildren = true;
412                                 break;
413                         }
414                 }
415                 return true;
416         }
417
418         ~TreeServer()
419         {
420                 /* We'd better tidy up after ourselves, eh? */
421                 this->DelHashEntry();
422         }
423 };
424
425 /* The Link class might as well be a struct,
426  * but this is C++ and we don't believe in structs (!).
427  * It holds the entire information of one <link>
428  * tag from the main config file. We maintain a list
429  * of them, and populate the list on rehash/load.
430  */
431
432 class Link
433 {
434  public:
435          std::string Name;
436          std::string IPAddr;
437          int Port;
438          std::string SendPass;
439          std::string RecvPass;
440          unsigned long AutoConnect;
441          time_t NextConnectTime;
442          std::string EncryptionKey;
443 };
444
445 /* The usual stuff for inspircd modules,
446  * plus the vector of Link classes which we
447  * use to store the <link> tags from the config
448  * file.
449  */
450 ConfigReader *Conf;
451 std::vector<Link> LinkBlocks;
452
453 /* Yay for fast searches!
454  * This is hundreds of times faster than recursion
455  * or even scanning a linked list, especially when
456  * there are more than a few servers to deal with.
457  * (read as: lots).
458  */
459 TreeServer* FindServer(std::string ServerName)
460 {
461         server_hash::iterator iter;
462         iter = serverlist.find(ServerName);
463         if (iter != serverlist.end())
464         {
465                 return iter->second;
466         }
467         else
468         {
469                 return NULL;
470         }
471 }
472
473 /* Returns the locally connected server we must route a
474  * message through to reach server 'ServerName'. This
475  * only applies to one-to-one and not one-to-many routing.
476  * See the comments for the constructor of TreeServer
477  * for more details.
478  */
479 TreeServer* BestRouteTo(std::string ServerName)
480 {
481         if (ServerName.c_str() == TreeRoot->GetName())
482                 return NULL;
483         TreeServer* Found = FindServer(ServerName);
484         if (Found)
485         {
486                 return Found->GetRoute();
487         }
488         else
489         {
490                 return NULL;
491         }
492 }
493
494 /* Find the first server matching a given glob mask.
495  * Theres no find-using-glob method of hash_map [awwww :-(]
496  * so instead, we iterate over the list using an iterator
497  * and match each one until we get a hit. Yes its slow,
498  * deal with it.
499  */
500 TreeServer* FindServerMask(std::string ServerName)
501 {
502         for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
503         {
504                 if (Srv->MatchText(i->first,ServerName))
505                         return i->second;
506         }
507         return NULL;
508 }
509
510 /* A convenient wrapper that returns true if a server exists */
511 bool IsServer(std::string ServerName)
512 {
513         return (FindServer(ServerName) != NULL);
514 }
515
516 /* Every SERVER connection inbound or outbound is represented by
517  * an object of type TreeSocket.
518  * TreeSockets, being inherited from InspSocket, can be tied into
519  * the core socket engine, and we cn therefore receive activity events
520  * for them, just like activex objects on speed. (yes really, that
521  * is a technical term!) Each of these which relates to a locally
522  * connected server is assocated with it, by hooking it onto a
523  * TreeSocket class using its constructor. In this way, we can
524  * maintain a list of servers, some of which are directly connected,
525  * some of which are not.
526  */
527
528 class TreeSocket : public InspSocket
529 {
530         std::string myhost;
531         std::string in_buffer;
532         ServerState LinkState;
533         std::string InboundServerName;
534         std::string InboundDescription;
535         int num_lost_users;
536         int num_lost_servers;
537         time_t NextPing;
538         bool LastPingWasGood;
539         bool bursting;
540         AES* ctx;
541         unsigned int keylength;
542         
543  public:
544
545         /* Because most of the I/O gubbins are encapsulated within
546          * InspSocket, we just call the superclass constructor for
547          * most of the action, and append a few of our own values
548          * to it.
549          */
550         TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
551                 : InspSocket(host, port, listening, maxtime)
552         {
553                 myhost = host;
554                 this->LinkState = LISTENER;
555         }
556
557         TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
558                 : InspSocket(host, port, listening, maxtime)
559         {
560                 myhost = ServerName;
561                 this->LinkState = CONNECTING;
562         }
563
564         /* When a listening socket gives us a new file descriptor,
565          * we must associate it with a socket without creating a new
566          * connection. This constructor is used for this purpose.
567          */
568         TreeSocket(int newfd, char* ip)
569                 : InspSocket(newfd, ip)
570         {
571                 this->LinkState = WAIT_AUTH_1;
572                 this->SendCapabilities();
573         }
574
575         void InitAES(std::string key,std::string SName)
576         {
577                 if (key == "")
578                         return;
579
580                 ctx = new AES();
581                 log(DEBUG,"Initialized AES key %s",key.c_str());
582                 // key must be 16, 24, 32 etc bytes (multiple of 8)
583                 keylength = key.length();
584                 if (!(keylength == 16 || keylength == 24 || keylength == 32))
585                 {
586                         WriteOpers("*** \2ERROR\2: Key length for encryptionkey is not 16, 24 or 32 bytes in length!");
587                         log(DEBUG,"Key length not 16, 24 or 32 characters!");
588                 }
589                 else
590                 {
591                         WriteOpers("*** \2AES\2: Initialized %d bit encryption to server %s",keylength*8,SName.c_str());
592                         ctx->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\
593                                 \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);
594                 }
595         }
596         
597         /* When an outbound connection finishes connecting, we receive
598          * this event, and must send our SERVER string to the other
599          * side. If the other side is happy, as outlined in the server
600          * to server docs on the inspircd.org site, the other side
601          * will then send back its own server string.
602          */
603         virtual bool OnConnected()
604         {
605                 if (this->LinkState == CONNECTING)
606                 {
607                         Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
608                         /* we do not need to change state here. */
609                         for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
610                         {
611                                 if (x->Name == this->myhost)
612                                 {
613                                         this->SendCapabilities();
614                                         if (x->EncryptionKey != "")
615                                         {
616                                                 if (!(x->EncryptionKey.length() == 16 || x->EncryptionKey.length() == 24 || x->EncryptionKey.length() == 32))
617                                                 {
618                                                         WriteOpers("\2WARNING\2: Your encryption key is NOT 16, 24 or 32 characters in length, encryption will \2NOT\2 be enabled.");
619                                                 }
620                                                 else
621                                                 {
622                                                         this->WriteLine("AES "+Srv->GetServerName());
623                                                         this->InitAES(x->EncryptionKey,x->Name);
624                                                 }
625                                         }
626                                         /* found who we're supposed to be connecting to, send the neccessary gubbins. */
627                                         this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
628                                         return true;
629                                 }
630                         }
631                 }
632                 /* There is a (remote) chance that between the /CONNECT and the connection
633                  * being accepted, some muppet has removed the <link> block and rehashed.
634                  * If that happens the connection hangs here until it's closed. Unlikely
635                  * and rather harmless.
636                  */
637                 return true;
638         }
639         
640         virtual void OnError(InspSocketError e)
641         {
642                 /* We don't handle this method, because all our
643                  * dirty work is done in OnClose() (see below)
644                  * which is still called on error conditions too.
645                  */
646         }
647
648         virtual int OnDisconnect()
649         {
650                 /* For the same reason as above, we don't
651                  * handle OnDisconnect()
652                  */
653                 return true;
654         }
655
656         /* Recursively send the server tree with distances as hops.
657          * This is used during network burst to inform the other server
658          * (and any of ITS servers too) of what servers we know about.
659          * If at any point any of these servers already exist on the other
660          * end, our connection may be terminated. The hopcounts given
661          * by this function are relative, this doesn't matter so long as
662          * they are all >1, as all the remote servers re-calculate them
663          * to be relative too, with themselves as hop 0.
664          */
665         void SendServers(TreeServer* Current, TreeServer* s, int hops)
666         {
667                 char command[1024];
668                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
669                 {
670                         TreeServer* recursive_server = Current->GetChild(q);
671                         if (recursive_server != s)
672                         {
673                                 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
674                                 this->WriteLine(command);
675                                 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
676                                 /* down to next level */
677                                 this->SendServers(recursive_server, s, hops+1);
678                         }
679                 }
680         }
681
682         std::string MyCapabilities()
683         {
684                 ServerConfig* Config = Srv->GetConfig();
685                 std::vector<std::string> modlist;
686                 std::string capabilities = "";
687
688                 for (int i = 0; i <= MODCOUNT; i++)
689                 {
690                         if ((modules[i]->GetVersion().Flags & VF_STATIC) || (modules[i]->GetVersion().Flags & VF_COMMON))
691                                 modlist.push_back(Config->module_names[i]);
692                 }
693                 sort(modlist.begin(),modlist.end());
694                 for (unsigned int i = 0; i < modlist.size(); i++)
695                 {
696                         if (i)
697                                 capabilities = capabilities + ",";
698                         capabilities = capabilities + modlist[i];
699                 }
700                 return capabilities;
701         }
702         
703         void SendCapabilities()
704         {
705                 this->WriteLine("CAPAB "+MyCapabilities());
706         }
707
708         bool Capab(std::deque<std::string> params)
709         {
710                 if (params.size() != 1)
711                 {
712                         this->WriteLine("ERROR :Invalid number of parameters for CAPAB");
713                         return false;
714                 }
715                 if (params[0] != this->MyCapabilities())
716                 {
717                         WriteOpers("*** \2ERROR\2: Server '%s' does not have the same set of modules loaded, cannot link!");
718                         WriteOpers("*** Our networked module set is: '%s'",this->MyCapabilities().c_str());
719                         WriteOpers("*** Other server's networked module set is: '%s'",params[0].c_str());
720                         WriteOpers("*** These lists must match exactly on both servers. Please correct these errors, and try again.");
721                         this->WriteLine("ERROR :CAPAB mismatch; My capabilities: '"+this->MyCapabilities()+"'");
722                         return false;
723                 }
724                 return true;
725         }
726
727         /* This function forces this server to quit, removing this server
728          * and any users on it (and servers and users below that, etc etc).
729          * It's very slow and pretty clunky, but luckily unless your network
730          * is having a REAL bad hair day, this function shouldnt be called
731          * too many times a month ;-)
732          */
733         void SquitServer(TreeServer* Current, CullList* Goners)
734         {
735                 /* recursively squit the servers attached to 'Current'.
736                  * We're going backwards so we don't remove users
737                  * while we still need them ;)
738                  */
739                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
740                 {
741                         TreeServer* recursive_server = Current->GetChild(q);
742                         this->SquitServer(recursive_server,Goners);
743                 }
744                 /* Now we've whacked the kids, whack self */
745                 num_lost_servers++;
746                 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
747                 {
748                         if (!strcasecmp(u->second->server,Current->GetName().c_str()))
749                         {
750                                 std::string qreason = Current->GetName()+" "+std::string(Srv->GetServerName());
751                                 Goners->AddItem(u->second,qreason);
752                                 num_lost_users++;
753                         }
754                 }
755         }
756
757         /* This is a wrapper function for SquitServer above, which
758          * does some validation first and passes on the SQUIT to all
759          * other remaining servers.
760          */
761         void Squit(TreeServer* Current,std::string reason)
762         {
763                 if ((Current) && (Current != TreeRoot))
764                 {
765                         std::deque<std::string> params;
766                         params.push_back(Current->GetName());
767                         params.push_back(":"+reason);
768                         DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
769                         if (Current->GetParent() == TreeRoot)
770                         {
771                                 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
772                         }
773                         else
774                         {
775                                 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
776                         }
777                         num_lost_servers = 0;
778                         num_lost_users = 0;
779                         CullList* Goners = new CullList();
780                         SquitServer(Current, Goners);
781                         Goners->Apply();
782                         Current->Tidy();
783                         Current->GetParent()->DelChild(Current);
784                         delete Current;
785                         delete Goners;
786                         WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
787                 }
788                 else
789                 {
790                         log(DEFAULT,"Squit from unknown server");
791                 }
792         }
793
794         /* FMODE command */
795         bool ForceMode(std::string source, std::deque<std::string> params)
796         {
797                 userrec* who = new userrec;
798                 who->fd = FD_MAGIC_NUMBER;
799                 if (params.size() < 2)
800                         return true;
801                 char* modelist[255];
802                 for (unsigned int q = 0; q < params.size(); q++)
803                 {
804                         modelist[q] = (char*)params[q].c_str();
805                 }
806                 Srv->SendMode(modelist,params.size(),who);
807                 DoOneToAllButSender(source,"FMODE",params,source);
808                 delete who;
809                 return true;
810         }
811
812         /* FTOPIC command */
813         bool ForceTopic(std::string source, std::deque<std::string> params)
814         {
815                 if (params.size() != 4)
816                         return true;
817                 std::string channel = params[0];
818                 time_t ts = atoi(params[1].c_str());
819                 std::string setby = params[2];
820                 std::string topic = params[3];
821
822                 chanrec* c = Srv->FindChannel(channel);
823                 if (c)
824                 {
825                         if ((ts >= c->topicset) || (!*c->topic))
826                         {
827                                 std::string oldtopic = c->topic;
828                                 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
829                                 strlcpy(c->setby,setby.c_str(),NICKMAX);
830                                 c->topicset = ts;
831                                 /* if the topic text is the same as the current topic,
832                                  * dont bother to send the TOPIC command out, just silently
833                                  * update the set time and set nick.
834                                  */
835                                 if (oldtopic != topic)
836                                         WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
837                         }
838                         
839                 }
840                 
841                 /* all done, send it on its way */
842                 params[3] = ":" + params[3];
843                 DoOneToAllButSender(source,"FTOPIC",params,source);
844
845                 return true;
846         }
847
848         /* FJOIN, similar to unreal SJOIN */
849         bool ForceJoin(std::string source, std::deque<std::string> params)
850         {
851                 if (params.size() < 3)
852                         return true;
853
854                 char first[MAXBUF];
855                 char modestring[MAXBUF];
856                 char* mode_users[127];
857                 mode_users[0] = first;
858                 mode_users[1] = modestring;
859                 strcpy(mode_users[1],"+");
860                 unsigned int modectr = 2;
861                 
862                 userrec* who = NULL;
863                 std::string channel = params[0];
864                 time_t TS = atoi(params[1].c_str());
865                 char* key = "";
866                 
867                 chanrec* chan = Srv->FindChannel(channel);
868                 if (chan)
869                 {
870                         key = chan->key;
871                 }
872                 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
873
874                 /* default is a high value, which if we dont have this
875                  * channel will let the other side apply their modes.
876                  */
877                 time_t ourTS = time(NULL)+600;
878                 chanrec* us = Srv->FindChannel(channel);
879                 if (us)
880                 {
881                         ourTS = us->age;
882                 }
883
884                 log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
885
886                 /* do this first, so our mode reversals are correctly received by other servers
887                  * if there is a TS collision.
888                  */
889                 DoOneToAllButSender(source,"FJOIN",params,source);
890                 
891                 for (unsigned int usernum = 2; usernum < params.size(); usernum++)
892                 {
893                         /* process one channel at a time, applying modes. */
894                         char* usr = (char*)params[usernum].c_str();
895                         char permissions = *usr;
896                         switch (permissions)
897                         {
898                                 case '@':
899                                         usr++;
900                                         mode_users[modectr++] = usr;
901                                         strlcat(modestring,"o",MAXBUF);
902                                 break;
903                                 case '%':
904                                         usr++;
905                                         mode_users[modectr++] = usr;
906                                         strlcat(modestring,"h",MAXBUF);
907                                 break;
908                                 case '+':
909                                         usr++;
910                                         mode_users[modectr++] = usr;
911                                         strlcat(modestring,"v",MAXBUF);
912                                 break;
913                         }
914                         who = Srv->FindNick(usr);
915                         if (who)
916                         {
917                                 Srv->JoinUserToChannel(who,channel,key);
918                                 if (modectr >= (MAXMODES-1))
919                                 {
920                                         /* theres a mode for this user. push them onto the mode queue, and flush it
921                                          * if there are more than MAXMODES to go.
922                                          */
923                                         if ((ourTS >= TS) || (Srv->IsUlined(who->server)))
924                                         {
925                                                 /* We also always let u-lined clients win, no matter what the TS value */
926                                                 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
927                                                 Srv->SendMode(mode_users,modectr,who);
928                                         }
929                                         else
930                                         {
931                                                 log(DEBUG,"Their channel newer than ours, bouncing their modes");
932                                                 /* bouncy bouncy! */
933                                                 std::deque<std::string> params;
934                                                 /* modes are now being UNSET... */
935                                                 *mode_users[1] = '-';
936                                                 for (unsigned int x = 0; x < modectr; x++)
937                                                 {
938                                                         params.push_back(mode_users[x]);
939                                                 }
940                                                 // tell everyone to bounce the modes. bad modes, bad!
941                                                 DoOneToMany(Srv->GetServerName(),"FMODE",params);
942                                         }
943                                         strcpy(mode_users[1],"+");
944                                         modectr = 2;
945                                 }
946                         }
947                 }
948                 /* there werent enough modes built up to flush it during FJOIN,
949                  * or, there are a number left over. flush them out.
950                  */
951                 if ((modectr > 2) && (who))
952                 {
953                         if (ourTS >= TS)
954                         {
955                                 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
956                                 Srv->SendMode(mode_users,modectr,who);
957                         }
958                         else
959                         {
960                                 log(DEBUG,"Their channel newer than ours, bouncing their modes");
961                                 std::deque<std::string> params;
962                                 *mode_users[1] = '-';
963                                 for (unsigned int x = 0; x < modectr; x++)
964                                 {
965                                         params.push_back(mode_users[x]);
966                                 }
967                                 DoOneToMany(Srv->GetServerName(),"FMODE",params);
968                         }
969                 }
970                 return true;
971         }
972
973         /* NICK command */
974         bool IntroduceClient(std::string source, std::deque<std::string> params)
975         {
976                 if (params.size() < 8)
977                         return true;
978                 // NICK age nick host dhost ident +modes ip :gecos
979                 //       0   1    2    3      4     5    6   7
980                 std::string nick = params[1];
981                 std::string host = params[2];
982                 std::string dhost = params[3];
983                 std::string ident = params[4];
984                 time_t age = atoi(params[0].c_str());
985                 std::string modes = params[5];
986                 while (*(modes.c_str()) == '+')
987                 {
988                         char* m = (char*)modes.c_str();
989                         m++;
990                         modes = m;
991                 }
992                 std::string ip = params[6];
993                 std::string gecos = params[7];
994                 char* tempnick = (char*)nick.c_str();
995                 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
996                 
997                 user_hash::iterator iter;
998                 iter = clientlist.find(tempnick);
999                 if (iter != clientlist.end())
1000                 {
1001                         // nick collision
1002                         log(DEBUG,"Nick collision on %s!%s@%s: %lu %lu",tempnick,ident.c_str(),host.c_str(),(unsigned long)age,(unsigned long)iter->second->age);
1003                         this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
1004                         return true;
1005                 }
1006
1007                 clientlist[tempnick] = new userrec();
1008                 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
1009                 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
1010                 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
1011                 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
1012                 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
1013                 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
1014                 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
1015                 clientlist[tempnick]->registered = 7;
1016                 clientlist[tempnick]->signon = age;
1017                 strlcpy(clientlist[tempnick]->modes, modes.c_str(),53);
1018                 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
1019
1020                 ucrec a;
1021                 a.channel = NULL;
1022                 a.uc_modes = 0;
1023                 for (int i = 0; i < MAXCHANS; i++)
1024                         clientlist[tempnick]->chans.push_back(a);
1025
1026                 if (!this->bursting)
1027                 {
1028                         WriteOpers("*** Client connecting at %s: %s!%s@%s [%s]",clientlist[tempnick]->server,clientlist[tempnick]->nick,clientlist[tempnick]->ident,clientlist[tempnick]->host,clientlist[tempnick]->ip);
1029                 }
1030                 params[7] = ":" + params[7];
1031                 DoOneToAllButSender(source,"NICK",params,source);
1032                 return true;
1033         }
1034
1035         /* Send one or more FJOINs for a channel of users.
1036          * If the length of a single line is more than 480-NICKMAX
1037          * in length, it is split over multiple lines.
1038          */
1039         void SendFJoins(TreeServer* Current, chanrec* c)
1040         {
1041                 log(DEBUG,"Sending FJOINs to other server for %s",c->name);
1042                 char list[MAXBUF];
1043                 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1044                 std::vector<char*> *ulist = c->GetUsers();
1045                 for (unsigned int i = 0; i < ulist->size(); i++)
1046                 {
1047                         char* o = (*ulist)[i];
1048                         userrec* otheruser = (userrec*)o;
1049                         strlcat(list," ",MAXBUF);
1050                         strlcat(list,cmode(otheruser,c),MAXBUF);
1051                         strlcat(list,otheruser->nick,MAXBUF);
1052                         if (strlen(list)>(480-NICKMAX))
1053                         {
1054                                 log(DEBUG,"FJOIN line wrapped");
1055                                 this->WriteLine(list);
1056                                 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1057                         }
1058                 }
1059                 if (list[strlen(list)-1] != ':')
1060                 {
1061                         log(DEBUG,"Final FJOIN line");
1062                         this->WriteLine(list);
1063                 }
1064         }
1065
1066         /* Send G, Q, Z and E lines */
1067         void SendXLines(TreeServer* Current)
1068         {
1069                 char data[MAXBUF];
1070                 /* Yes, these arent too nice looking, but they get the job done */
1071                 for (std::vector<ZLine>::iterator i = zlines.begin(); i != zlines.end(); i++)
1072                 {
1073                         snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->ipaddr,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1074                         this->WriteLine(data);
1075                 }
1076                 for (std::vector<QLine>::iterator i = qlines.begin(); i != qlines.end(); i++)
1077                 {
1078                         snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->nick,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1079                         this->WriteLine(data);
1080                 }
1081                 for (std::vector<GLine>::iterator i = glines.begin(); i != glines.end(); i++)
1082                 {
1083                         snprintf(data,MAXBUF,":%s ADDLINE G %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1084                         this->WriteLine(data);
1085                 }
1086                 for (std::vector<ELine>::iterator i = elines.begin(); i != elines.end(); i++)
1087                 {
1088                         snprintf(data,MAXBUF,":%s ADDLINE E %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1089                         this->WriteLine(data);
1090                 }
1091                 for (std::vector<ZLine>::iterator i = pzlines.begin(); i != pzlines.end(); i++)
1092                 {
1093                         snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->ipaddr,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1094                         this->WriteLine(data);
1095                 }
1096                 for (std::vector<QLine>::iterator i = pqlines.begin(); i != pqlines.end(); i++)
1097                 {
1098                         snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->nick,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1099                         this->WriteLine(data);
1100                 }
1101                 for (std::vector<GLine>::iterator i = pglines.begin(); i != pglines.end(); i++)
1102                 {
1103                         snprintf(data,MAXBUF,":%s ADDLINE G %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1104                         this->WriteLine(data);
1105                 }
1106                 for (std::vector<ELine>::iterator i = pelines.begin(); i != pelines.end(); i++)
1107                 {
1108                         snprintf(data,MAXBUF,":%s ADDLINE E %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1109                         this->WriteLine(data);
1110                 }
1111         }
1112
1113         /* Send channel modes and topics */
1114         void SendChannelModes(TreeServer* Current)
1115         {
1116                 char data[MAXBUF];
1117                 std::deque<std::string> list;
1118                 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
1119                 {
1120                         SendFJoins(Current, c->second);
1121                         snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
1122                         this->WriteLine(data);
1123                         if (*c->second->topic)
1124                         {
1125                                 snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",Srv->GetServerName().c_str(),c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
1126                                 this->WriteLine(data);
1127                         }
1128                         for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
1129                         {
1130                                 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
1131                                 this->WriteLine(data);
1132                         }
1133                         FOREACH_MOD OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this);
1134                         list.clear();
1135                         c->second->GetExtList(list);
1136                         for (unsigned int j = 0; j < list.size(); j++)
1137                         {
1138                                 FOREACH_MOD OnSyncChannelMetaData(c->second,(Module*)TreeProtocolModule,(void*)this,list[j]);
1139                         }
1140                 }
1141         }
1142
1143         /* send all users and their oper state/modes */
1144         void SendUsers(TreeServer* Current)
1145         {
1146                 char data[MAXBUF];
1147                 std::deque<std::string> list;
1148                 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
1149                 {
1150                         if (u->second->registered == 7)
1151                         {
1152                                 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->modes,u->second->ip,u->second->fullname);
1153                                 this->WriteLine(data);
1154                                 if (strchr(u->second->modes,'o'))
1155                                 {
1156                                         this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
1157                                 }
1158                                 FOREACH_MOD OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this);
1159                                 list.clear();
1160                                 u->second->GetExtList(list);
1161                                 for (unsigned int j = 0; j < list.size(); j++)
1162                                 {
1163                                         FOREACH_MOD OnSyncUserMetaData(u->second,(Module*)TreeProtocolModule,(void*)this,list[j]);
1164                                 }
1165                         }
1166                 }
1167         }
1168
1169         /* This function is called when we want to send a netburst to a local
1170          * server. There is a set order we must do this, because for example
1171          * users require their servers to exist, and channels require their
1172          * users to exist. You get the idea.
1173          */
1174         void DoBurst(TreeServer* s)
1175         {
1176                 Srv->SendOpers("*** Bursting to \2"+s->GetName()+"\2.");
1177                 this->WriteLine("BURST");
1178                 /* send our version string */
1179                 this->WriteLine(":"+Srv->GetServerName()+" VERSION :"+Srv->GetVersion());
1180                 /* Send server tree */
1181                 this->SendServers(TreeRoot,s,1);
1182                 /* Send users and their oper status */
1183                 this->SendUsers(s);
1184                 /* Send everything else (channel modes, xlines etc) */
1185                 this->SendChannelModes(s);
1186                 this->SendXLines(s);
1187                 this->WriteLine("ENDBURST");
1188                 Srv->SendOpers("*** Finished bursting to \2"+s->GetName()+"\2.");
1189         }
1190
1191         /* This function is called when we receive data from a remote
1192          * server. We buffer the data in a std::string (it doesnt stay
1193          * there for long), reading using InspSocket::Read() which can
1194          * read up to 16 kilobytes in one operation.
1195          *
1196          * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
1197          * THE SOCKET OBJECT FOR US.
1198          */
1199         virtual bool OnDataReady()
1200         {
1201                 char* data = this->Read();
1202                 if (data)
1203                 {
1204                         this->in_buffer += data;
1205                         /* While there is at least one new line in the buffer,
1206                          * do something useful (we hope!) with it.
1207                          */
1208                         while (in_buffer.find("\n") != std::string::npos)
1209                         {
1210                                 char* line = (char*)in_buffer.c_str();
1211                                 std::string ret = "";
1212                                 while ((*line != '\n') && (strlen(line)))
1213                                 {
1214                                         ret = ret + *line;
1215                                         line++;
1216                                 }
1217                                 if ((*line == '\n') || (*line == '\r'))
1218                                         line++;
1219                                 in_buffer = line;
1220                                 /* Process this one, abort if it
1221                                  * didnt return true.
1222                                  */
1223                                 if (this->ctx)
1224                                 {
1225                                         char out[1024];
1226                                         char result[1024];
1227                                         log(DEBUG,"Original string '%s'",ret.c_str());
1228                                         int nbytes = from64tobits(out, ret.c_str(), 1024);
1229                                         log(DEBUG,"m_spanningtree: decrypt %d bytes",nbytes);
1230                                         ctx->Decrypt(out, result, nbytes, 0);
1231                                         for (int t = 0; t < nbytes; t++)
1232                                                 if (result[t] == '\7') result[t] = 0;
1233                                         ret = result;
1234                                 }
1235                                 if (!this->ProcessLine(ret))
1236                                 {
1237                                         return false;
1238                                 }
1239                         }
1240                 }
1241                 return (data != NULL);
1242         }
1243
1244         int WriteLine(std::string line)
1245         {
1246                 log(DEBUG,"OUT: %s",line.c_str());
1247                 if (this->ctx)
1248                 {
1249                         log(DEBUG,"AES context");
1250                         char result[1024];
1251                         char result64[1024];
1252                         if (this->keylength)
1253                         {
1254                                 while (line.length() % this->keylength != 0)
1255                                 {
1256                                         // pad it to be a multiple of the key length
1257                                         line = line + "\7";
1258                                 }
1259                         }
1260                         ctx->Encrypt(line.c_str(), result, line.length(),0);
1261                         to64frombits((unsigned char*)result64,
1262                                         (unsigned char*)result,
1263                                         line.length());
1264                         line = result64;
1265                         log(DEBUG,"Encrypted: %s",line.c_str());
1266                         //int from64tobits(char *out, const char *in, int maxlen);
1267                 }
1268                 return this->Write(line + "\r\n");
1269         }
1270
1271         /* Handle ERROR command */
1272         bool Error(std::deque<std::string> params)
1273         {
1274                 if (params.size() < 1)
1275                         return false;
1276                 std::string Errmsg = params[0];
1277                 std::string SName = myhost;
1278                 if (InboundServerName != "")
1279                 {
1280                         SName = InboundServerName;
1281                 }
1282                 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
1283                 /* we will return false to cause the socket to close.
1284                  */
1285                 return false;
1286         }
1287
1288         /* Because the core won't let users or even SERVERS set +o,
1289          * we use the OPERTYPE command to do this.
1290          */
1291         bool OperType(std::string prefix, std::deque<std::string> &params)
1292         {
1293                 if (params.size() != 1)
1294                         return true;
1295                 std::string opertype = params[0];
1296                 userrec* u = Srv->FindNick(prefix);
1297                 if (u)
1298                 {
1299                         strlcpy(u->oper,opertype.c_str(),NICKMAX);
1300                         if (!strchr(u->modes,'o'))
1301                         {
1302                                 strcat(u->modes,"o");
1303                         }
1304                         DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
1305                 }
1306                 return true;
1307         }
1308
1309         /* Because Andy insists that services-compatible servers must
1310          * implement SVSNICK and SVSJOIN, that's exactly what we do :p
1311          */
1312         bool ForceNick(std::string prefix, std::deque<std::string> &params)
1313         {
1314                 if (params.size() < 3)
1315                         return true;
1316                 userrec* u = Srv->FindNick(params[0]);
1317                 if (u)
1318                 {
1319                         Srv->ChangeUserNick(u,params[1]);
1320                         u->age = atoi(params[2].c_str());
1321                         DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
1322                 }
1323                 return true;
1324         }
1325
1326         bool ServiceJoin(std::string prefix, std::deque<std::string> &params)
1327         {
1328                 if (params.size() < 2)
1329                         return true;
1330                 userrec* u = Srv->FindNick(params[0]);
1331                 if (u)
1332                 {
1333                         Srv->JoinUserToChannel(u,params[1],"");
1334                         DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
1335                 }
1336                 return true;
1337         }
1338
1339         bool RemoteRehash(std::string prefix, std::deque<std::string> &params)
1340         {
1341                 if (params.size() < 1)
1342                         return false;
1343                 std::string servermask = params[0];
1344                 if (Srv->MatchText(Srv->GetServerName(),servermask))
1345                 {
1346                         Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
1347                         Srv->RehashServer();
1348                         ReadConfiguration(false);
1349                 }
1350                 DoOneToAllButSender(prefix,"REHASH",params,prefix);
1351                 return true;
1352         }
1353
1354         bool RemoteKill(std::string prefix, std::deque<std::string> &params)
1355         {
1356                 if (params.size() != 2)
1357                         return true;
1358                 std::string nick = params[0];
1359                 userrec* u = Srv->FindNick(prefix);
1360                 userrec* who = Srv->FindNick(nick);
1361                 if (who)
1362                 {
1363                         /* Prepend kill source, if we don't have one */
1364                         std::string sourceserv = prefix;
1365                         if (u)
1366                         {
1367                                 sourceserv = u->server;
1368                         }
1369                         if (*(params[1].c_str()) != '[')
1370                         {
1371                                 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
1372                         }
1373                         std::string reason = params[1];
1374                         params[1] = ":" + params[1];
1375                         DoOneToAllButSender(prefix,"KILL",params,sourceserv);
1376                         Srv->QuitUser(who,reason);
1377                 }
1378                 return true;
1379         }
1380
1381         bool LocalPong(std::string prefix, std::deque<std::string> &params)
1382         {
1383                 if (params.size() < 1)
1384                         return true;
1385                 TreeServer* ServerSource = FindServer(prefix);
1386                 if (ServerSource)
1387                 {
1388                         ServerSource->SetPingFlag();
1389                 }
1390                 return true;
1391         }
1392         
1393         bool MetaData(std::string prefix, std::deque<std::string> &params)
1394         {
1395                 if (params.size() < 3)
1396                         return true;
1397                 TreeServer* ServerSource = FindServer(prefix);
1398                 if (ServerSource)
1399                 {
1400                         if (*(params[0].c_str()) == '#')
1401                         {
1402                                 chanrec* c = Srv->FindChannel(params[0]);
1403                                 if (c)
1404                                 {
1405                                         FOREACH_MOD OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]);
1406                                 }
1407                         }
1408                         else
1409                         {
1410                                 userrec* u = Srv->FindNick(params[0]);
1411                                 if (u)
1412                                 {
1413                                         FOREACH_MOD OnDecodeMetaData(TYPE_USER,u,params[1],params[2]);
1414                                 }
1415                         }
1416                 }
1417                 params[2] = ":" + params[2];
1418                 DoOneToAllButSender(prefix,"METADATA",params,prefix);
1419                 return true;
1420         }
1421
1422         bool ServerVersion(std::string prefix, std::deque<std::string> &params)
1423         {
1424                 if (params.size() < 1)
1425                         return true;
1426                 TreeServer* ServerSource = FindServer(prefix);
1427                 if (ServerSource)
1428                 {
1429                         ServerSource->SetVersion(params[0]);
1430                 }
1431                 params[0] = ":" + params[0];
1432                 DoOneToAllButSender(prefix,"VERSION",params,prefix);
1433                 return true;
1434         }
1435
1436         bool ChangeHost(std::string prefix, std::deque<std::string> &params)
1437         {
1438                 if (params.size() < 1)
1439                         return true;
1440                 userrec* u = Srv->FindNick(prefix);
1441                 if (u)
1442                 {
1443                         Srv->ChangeHost(u,params[0]);
1444                         DoOneToAllButSender(prefix,"FHOST",params,u->server);
1445                 }
1446                 return true;
1447         }
1448
1449         bool AddLine(std::string prefix, std::deque<std::string> &params)
1450         {
1451                 if (params.size() < 6)
1452                         return true;
1453                 std::string linetype = params[0]; /* Z, Q, E, G, K */
1454                 std::string mask = params[1]; /* Line type dependent */
1455                 std::string source = params[2]; /* may not be online or may be a server */
1456                 std::string settime = params[3]; /* EPOCH time set */
1457                 std::string duration = params[4]; /* Duration secs */
1458                 std::string reason = params[5];
1459
1460                 switch (*(linetype.c_str()))
1461                 {
1462                         case 'Z':
1463                                 add_zline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1464                                 zline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1465                         break;
1466                         case 'Q':
1467                                 add_qline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1468                                 qline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1469                         break;
1470                         case 'E':
1471                                 add_eline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1472                                 eline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1473                         break;
1474                         case 'G':
1475                                 add_gline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1476                                 gline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1477                         break;
1478                         case 'K':
1479                                 add_kline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1480                         break;
1481                         default:
1482                                 /* Just in case... */
1483                                 Srv->SendOpers("*** \2WARNING\2: Invalid xline type '"+linetype+"' sent by server "+prefix+", ignored!");
1484                         break;
1485                 }
1486                 /* Send it on its way */
1487                 params[5] = ":" + params[5];
1488                 DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
1489                 return true;
1490         }
1491
1492         bool ChangeName(std::string prefix, std::deque<std::string> &params)
1493         {
1494                 if (params.size() < 1)
1495                         return true;
1496                 userrec* u = Srv->FindNick(prefix);
1497                 if (u)
1498                 {
1499                         Srv->ChangeGECOS(u,params[0]);
1500                         params[0] = ":" + params[0];
1501                         DoOneToAllButSender(prefix,"FNAME",params,u->server);
1502                 }
1503                 return true;
1504         }
1505
1506         bool Whois(std::string prefix, std::deque<std::string> &params)
1507         {
1508                 if (params.size() < 1)
1509                         return true;
1510                 log(DEBUG,"In IDLE command");
1511                 userrec* u = Srv->FindNick(prefix);
1512                 if (u)
1513                 {
1514                         log(DEBUG,"USER EXISTS: %s",u->nick);
1515                         // an incoming request
1516                         if (params.size() == 1)
1517                         {
1518                                 userrec* x = Srv->FindNick(params[0]);
1519                                 if (x->fd > -1)
1520                                 {
1521                                         userrec* x = Srv->FindNick(params[0]);
1522                                         log(DEBUG,"Got IDLE");
1523                                         char signon[MAXBUF];
1524                                         char idle[MAXBUF];
1525                                         log(DEBUG,"Sending back IDLE 3");
1526                                         snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
1527                                         snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-time(NULL)));
1528                                         std::deque<std::string> par;
1529                                         par.push_back(prefix);
1530                                         par.push_back(signon);
1531                                         par.push_back(idle);
1532                                         // ours, we're done, pass it BACK
1533                                         DoOneToOne(params[0],"IDLE",par,u->server);
1534                                 }
1535                                 else
1536                                 {
1537                                         // not ours pass it on
1538                                         DoOneToOne(prefix,"IDLE",params,x->server);
1539                                 }
1540                         }
1541                         else if (params.size() == 3)
1542                         {
1543                                 std::string who_did_the_whois = params[0];
1544                                 userrec* who_to_send_to = Srv->FindNick(who_did_the_whois);
1545                                 if (who_to_send_to->fd > -1)
1546                                 {
1547                                         log(DEBUG,"Got final IDLE");
1548                                         // an incoming reply to a whois we sent out
1549                                         std::string nick_whoised = prefix;
1550                                         unsigned long signon = atoi(params[1].c_str());
1551                                         unsigned long idle = atoi(params[2].c_str());
1552                                         if ((who_to_send_to) && (who_to_send_to->fd > -1))
1553                                                 do_whois(who_to_send_to,u,signon,idle,(char*)nick_whoised.c_str());
1554                                 }
1555                                 else
1556                                 {
1557                                         // not ours, pass it on
1558                                         DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
1559                                 }
1560                         }
1561                 }
1562                 return true;
1563         }
1564         
1565         bool LocalPing(std::string prefix, std::deque<std::string> &params)
1566         {
1567                 if (params.size() < 1)
1568                         return true;
1569                 std::string stufftobounce = params[0];
1570                 this->WriteLine(":"+Srv->GetServerName()+" PONG "+stufftobounce);
1571                 return true;
1572         }
1573
1574         bool RemoteServer(std::string prefix, std::deque<std::string> &params)
1575         {
1576                 if (params.size() < 4)
1577                         return false;
1578                 std::string servername = params[0];
1579                 std::string password = params[1];
1580                 // hopcount is not used for a remote server, we calculate this ourselves
1581                 std::string description = params[3];
1582                 TreeServer* ParentOfThis = FindServer(prefix);
1583                 if (!ParentOfThis)
1584                 {
1585                         this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
1586                         return false;
1587                 }
1588                 TreeServer* CheckDupe = FindServer(servername);
1589                 if (CheckDupe)
1590                 {
1591                         this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1592                         Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1593                         return false;
1594                 }
1595                 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
1596                 ParentOfThis->AddChild(Node);
1597                 params[3] = ":" + params[3];
1598                 DoOneToAllButSender(prefix,"SERVER",params,prefix);
1599                 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
1600                 return true;
1601         }
1602
1603         bool Outbound_Reply_Server(std::deque<std::string> &params)
1604         {
1605                 if (params.size() < 4)
1606                         return false;
1607                 std::string servername = params[0];
1608                 std::string password = params[1];
1609                 int hops = atoi(params[2].c_str());
1610                 if (hops)
1611                 {
1612                         this->WriteLine("ERROR :Server too far away for authentication");
1613                         Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, server is too far away for authentication");
1614                         return false;
1615                 }
1616                 std::string description = params[3];
1617                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1618                 {
1619                         if ((x->Name == servername) && (x->RecvPass == password))
1620                         {
1621                                 TreeServer* CheckDupe = FindServer(servername);
1622                                 if (CheckDupe)
1623                                 {
1624                                         this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1625                                         Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1626                                         return false;
1627                                 }
1628                                 // Begin the sync here. this kickstarts the
1629                                 // other side, waiting in WAIT_AUTH_2 state,
1630                                 // into starting their burst, as it shows
1631                                 // that we're happy.
1632                                 this->LinkState = CONNECTED;
1633                                 // we should add the details of this server now
1634                                 // to the servers tree, as a child of the root
1635                                 // node.
1636                                 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
1637                                 TreeRoot->AddChild(Node);
1638                                 params[3] = ":" + params[3];
1639                                 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
1640                                 this->bursting = true;
1641                                 this->DoBurst(Node);
1642                                 return true;
1643                         }
1644                 }
1645                 this->WriteLine("ERROR :Invalid credentials");
1646                 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, invalid link credentials");
1647                 return false;
1648         }
1649
1650         bool Inbound_Server(std::deque<std::string> &params)
1651         {
1652                 if (params.size() < 4)
1653                         return false;
1654                 std::string servername = params[0];
1655                 std::string password = params[1];
1656                 int hops = atoi(params[2].c_str());
1657                 if (hops)
1658                 {
1659                         this->WriteLine("ERROR :Server too far away for authentication");
1660                         Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, server is too far away for authentication");
1661                         return false;
1662                 }
1663                 std::string description = params[3];
1664                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1665                 {
1666                         if ((x->Name == servername) && (x->RecvPass == password))
1667                         {
1668                                 TreeServer* CheckDupe = FindServer(servername);
1669                                 if (CheckDupe)
1670                                 {
1671                                         this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1672                                         Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1673                                         return false;
1674                                 }
1675                                 /* If the config says this link is encrypted, but the remote side
1676                                  * hasnt bothered to send the AES command before SERVER, then we
1677                                  * boot them off as we MUST have this connection encrypted.
1678                                  */
1679                                 if ((x->EncryptionKey != "") && (!this->ctx))
1680                                 {
1681                                         this->WriteLine("ERROR :This link requires AES encryption to be enabled. Plaintext connection refused.");
1682                                         Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, remote server did not enable AES.");
1683                                         return false;
1684                                 }
1685                                 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
1686                                 this->InboundServerName = servername;
1687                                 this->InboundDescription = description;
1688                                 // this is good. Send our details: Our server name and description and hopcount of 0,
1689                                 // along with the sendpass from this block.
1690                                 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
1691                                 // move to the next state, we are now waiting for THEM.
1692                                 this->LinkState = WAIT_AUTH_2;
1693                                 return true;
1694                         }
1695                 }
1696                 this->WriteLine("ERROR :Invalid credentials");
1697                 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, invalid link credentials");
1698                 return false;
1699         }
1700
1701         void Split(std::string line, bool stripcolon, std::deque<std::string> &n)
1702         {
1703                 if (!strchr(line.c_str(),' '))
1704                 {
1705                         n.push_back(line);
1706                         return;
1707                 }
1708                 std::stringstream s(line);
1709                 std::string param = "";
1710                 n.clear();
1711                 int item = 0;
1712                 while (!s.eof())
1713                 {
1714                         char c;
1715                         s.get(c);
1716                         if (c == ' ')
1717                         {
1718                                 n.push_back(param);
1719                                 param = "";
1720                                 item++;
1721                         }
1722                         else
1723                         {
1724                                 if (!s.eof())
1725                                 {
1726                                         param = param + c;
1727                                 }
1728                                 if ((param == ":") && (item > 0))
1729                                 {
1730                                         param = "";
1731                                         while (!s.eof())
1732                                         {
1733                                                 s.get(c);
1734                                                 if (!s.eof())
1735                                                 {
1736                                                         param = param + c;
1737                                                 }
1738                                         }
1739                                         n.push_back(param);
1740                                         param = "";
1741                                 }
1742                         }
1743                 }
1744                 if (param != "")
1745                 {
1746                         n.push_back(param);
1747                 }
1748                 return;
1749         }
1750
1751         bool ProcessLine(std::string line)
1752         {
1753                 char* l = (char*)line.c_str();
1754                 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
1755                         l[strlen(l)-1] = '\0';
1756                 line = l;
1757                 if (line == "")
1758                         return true;
1759                 Srv->Log(DEBUG,"IN: "+line);
1760                 std::deque<std::string> params;
1761                 this->Split(line,true,params);
1762                 std::string command = "";
1763                 std::string prefix = "";
1764                 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
1765                 {
1766                         prefix = params[0];
1767                         command = params[1];
1768                         char* pref = (char*)prefix.c_str();
1769                         prefix = ++pref;
1770                         params.pop_front();
1771                         params.pop_front();
1772                 }
1773                 else
1774                 {
1775                         prefix = "";
1776                         command = params[0];
1777                         params.pop_front();
1778                 }
1779
1780                 if ((!this->ctx) && (command == "AES"))
1781                 {
1782                         std::string sserv = params[0];
1783                         for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1784                         {
1785                                 if ((x->EncryptionKey != "") && (x->Name == sserv))
1786                                 {
1787                                         this->InitAES(x->EncryptionKey,sserv);
1788                                 }
1789                         }
1790                         return true;
1791                 }
1792                 else if ((this->ctx) && (command == "AES"))
1793                 {
1794                         WriteOpers("*** \2AES\2: Encryption already enabled on this connection yet %s is trying to enable it twice!",params[0].c_str());
1795                 }
1796
1797                 switch (this->LinkState)
1798                 {
1799                         TreeServer* Node;
1800                         
1801                         case WAIT_AUTH_1:
1802                                 // Waiting for SERVER command from remote server. Server initiating
1803                                 // the connection sends the first SERVER command, listening server
1804                                 // replies with theirs if its happy, then if the initiator is happy,
1805                                 // it starts to send its net sync, which starts the merge, otherwise
1806                                 // it sends an ERROR.
1807                                 if (command == "PASS")
1808                                 {
1809                                         /* Silently ignored */
1810                                 }
1811                                 else if (command == "SERVER")
1812                                 {
1813                                         return this->Inbound_Server(params);
1814                                 }
1815                                 else if (command == "ERROR")
1816                                 {
1817                                         return this->Error(params);
1818                                 }
1819                                 else if (command == "USER")
1820                                 {
1821                                         this->WriteLine("ERROR :Client connections to this port are prohibited.");
1822                                         return false;
1823                                 }
1824                                 else if (command == "CAPAB")
1825                                 {
1826                                         return this->Capab(params);
1827                                 }
1828                                 else
1829                                 {
1830                                         this->WriteLine("ERROR :Invalid command in negotiation phase.");
1831                                         return false;
1832                                 }
1833                         break;
1834                         case WAIT_AUTH_2:
1835                                 // Waiting for start of other side's netmerge to say they liked our
1836                                 // password.
1837                                 if (command == "SERVER")
1838                                 {
1839                                         // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1840                                         // silently ignore.
1841                                         return true;
1842                                 }
1843                                 else if (command == "BURST")
1844                                 {
1845                                         this->LinkState = CONNECTED;
1846                                         Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
1847                                         TreeRoot->AddChild(Node);
1848                                         params.clear();
1849                                         params.push_back(InboundServerName);
1850                                         params.push_back("*");
1851                                         params.push_back("1");
1852                                         params.push_back(":"+InboundDescription);
1853                                         DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
1854                                         this->bursting = true;
1855                                         this->DoBurst(Node);
1856                                 }
1857                                 else if (command == "ERROR")
1858                                 {
1859                                         return this->Error(params);
1860                                 }
1861                                 else if (command == "CAPAB")
1862                                 {
1863                                         return this->Capab(params);
1864                                 }
1865                                 
1866                         break;
1867                         case LISTENER:
1868                                 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
1869                                 return false;
1870                         break;
1871                         case CONNECTING:
1872                                 if (command == "SERVER")
1873                                 {
1874                                         // another server we connected to, which was in WAIT_AUTH_1 state,
1875                                         // has just sent us their credentials. If we get this far, theyre
1876                                         // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1877                                         // if we're happy with this, we should send our netburst which
1878                                         // kickstarts the merge.
1879                                         return this->Outbound_Reply_Server(params);
1880                                 }
1881                                 else if (command == "ERROR")
1882                                 {
1883                                         return this->Error(params);
1884                                 }
1885                         break;
1886                         case CONNECTED:
1887                                 // This is the 'authenticated' state, when all passwords
1888                                 // have been exchanged and anything past this point is taken
1889                                 // as gospel.
1890                                 
1891                                 if (prefix != "")
1892                                 {
1893                                         std::string direction = prefix;
1894                                         userrec* t = Srv->FindNick(prefix);
1895                                         if (t)
1896                                         {
1897                                                 direction = t->server;
1898                                         }
1899                                         TreeServer* route_back_again = BestRouteTo(direction);
1900                                         if ((!route_back_again) || (route_back_again->GetSocket() != this))
1901                                         {
1902                                                 if (route_back_again)
1903                                                 {
1904                                                         WriteOpers("*** Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
1905                                                 }
1906                                                 else
1907                                                 {
1908                                                         WriteOpers("*** Protocol violation: Invalid source '%s' in command '%s' from connection '%s'",direction.c_str(),line.c_str(),this->GetName().c_str());
1909                                                 }
1910                                                 
1911                                                 return true;
1912                                         }
1913                                 }
1914                                 
1915                                 if (command == "SVSMODE")
1916                                 {
1917                                         /* Services expects us to implement
1918                                          * SVSMODE. In inspircd its the same as
1919                                          * MODE anyway.
1920                                          */
1921                                         command = "MODE";
1922                                 }
1923                                 std::string target = "";
1924                                 /* Yes, know, this is a mess. Its reasonably fast though as we're
1925                                  * working with std::string here.
1926                                  */
1927                                 if ((command == "NICK") && (params.size() > 1))
1928                                 {
1929                                         return this->IntroduceClient(prefix,params);
1930                                 }
1931                                 else if (command == "FJOIN")
1932                                 {
1933                                         return this->ForceJoin(prefix,params);
1934                                 }
1935                                 else if (command == "SERVER")
1936                                 {
1937                                         return this->RemoteServer(prefix,params);
1938                                 }
1939                                 else if (command == "ERROR")
1940                                 {
1941                                         return this->Error(params);
1942                                 }
1943                                 else if (command == "OPERTYPE")
1944                                 {
1945                                         return this->OperType(prefix,params);
1946                                 }
1947                                 else if (command == "FMODE")
1948                                 {
1949                                         return this->ForceMode(prefix,params);
1950                                 }
1951                                 else if (command == "KILL")
1952                                 {
1953                                         return this->RemoteKill(prefix,params);
1954                                 }
1955                                 else if (command == "FTOPIC")
1956                                 {
1957                                         return this->ForceTopic(prefix,params);
1958                                 }
1959                                 else if (command == "REHASH")
1960                                 {
1961                                         return this->RemoteRehash(prefix,params);
1962                                 }
1963                                 else if (command == "METADATA")
1964                                 {
1965                                         return this->MetaData(prefix,params);
1966                                 }
1967                                 else if (command == "PING")
1968                                 {
1969                                         return this->LocalPing(prefix,params);
1970                                 }
1971                                 else if (command == "PONG")
1972                                 {
1973                                         return this->LocalPong(prefix,params);
1974                                 }
1975                                 else if (command == "VERSION")
1976                                 {
1977                                         return this->ServerVersion(prefix,params);
1978                                 }
1979                                 else if (command == "FHOST")
1980                                 {
1981                                         return this->ChangeHost(prefix,params);
1982                                 }
1983                                 else if (command == "FNAME")
1984                                 {
1985                                         return this->ChangeName(prefix,params);
1986                                 }
1987                                 else if (command == "ADDLINE")
1988                                 {
1989                                         return this->AddLine(prefix,params);
1990                                 }
1991                                 else if (command == "SVSNICK")
1992                                 {
1993                                         if (prefix == "")
1994                                         {
1995                                                 prefix = this->GetName();
1996                                         }
1997                                         return this->ForceNick(prefix,params);
1998                                 }
1999                                 else if (command == "IDLE")
2000                                 {
2001                                         return this->Whois(prefix,params);
2002                                 }
2003                                 else if (command == "SVSJOIN")
2004                                 {
2005                                         if (prefix == "")
2006                                         {
2007                                                 prefix = this->GetName();
2008                                         }
2009                                         return this->ServiceJoin(prefix,params);
2010                                 }
2011                                 else if (command == "SQUIT")
2012                                 {
2013                                         if (params.size() == 2)
2014                                         {
2015                                                 this->Squit(FindServer(params[0]),params[1]);
2016                                         }
2017                                         return true;
2018                                 }
2019                                 else if (command == "ENDBURST")
2020                                 {
2021                                         this->bursting = false;
2022                                         return true;
2023                                 }
2024                                 else
2025                                 {
2026                                         // not a special inter-server command.
2027                                         // Emulate the actual user doing the command,
2028                                         // this saves us having a huge ugly parser.
2029                                         userrec* who = Srv->FindNick(prefix);
2030                                         std::string sourceserv = this->myhost;
2031                                         if (this->InboundServerName != "")
2032                                         {
2033                                                 sourceserv = this->InboundServerName;
2034                                         }
2035                                         if (who)
2036                                         {
2037                                                 // its a user
2038                                                 target = who->server;
2039                                                 char* strparams[127];
2040                                                 for (unsigned int q = 0; q < params.size(); q++)
2041                                                 {
2042                                                         strparams[q] = (char*)params[q].c_str();
2043                                                 }
2044                                                 Srv->CallCommandHandler(command, strparams, params.size(), who);
2045                                         }
2046                                         else
2047                                         {
2048                                                 // its not a user. Its either a server, or somethings screwed up.
2049                                                 if (IsServer(prefix))
2050                                                 {
2051                                                         target = Srv->GetServerName();
2052                                                 }
2053                                                 else
2054                                                 {
2055                                                         log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
2056                                                         return true;
2057                                                 }
2058                                         }
2059                                         return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
2060
2061                                 }
2062                                 return true;
2063                         break;
2064                 }
2065                 return true;
2066         }
2067
2068         virtual std::string GetName()
2069         {
2070                 std::string sourceserv = this->myhost;
2071                 if (this->InboundServerName != "")
2072                 {
2073                         sourceserv = this->InboundServerName;
2074                 }
2075                 return sourceserv;
2076         }
2077
2078         virtual void OnTimeout()
2079         {
2080                 if (this->LinkState == CONNECTING)
2081                 {
2082                         Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
2083                 }
2084         }
2085
2086         virtual void OnClose()
2087         {
2088                 // Connection closed.
2089                 // If the connection is fully up (state CONNECTED)
2090                 // then propogate a netsplit to all peers.
2091                 std::string quitserver = this->myhost;
2092                 if (this->InboundServerName != "")
2093                 {
2094                         quitserver = this->InboundServerName;
2095                 }
2096                 TreeServer* s = FindServer(quitserver);
2097                 if (s)
2098                 {
2099                         Squit(s,"Remote host closed the connection");
2100                 }
2101         }
2102
2103         virtual int OnIncomingConnection(int newsock, char* ip)
2104         {
2105                 TreeSocket* s = new TreeSocket(newsock, ip);
2106                 Srv->AddSocket(s);
2107                 return true;
2108         }
2109 };
2110
2111 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
2112 {
2113         for (unsigned int c = 0; c < list.size(); c++)
2114         {
2115                 if (list[c] == server)
2116                 {
2117                         return;
2118                 }
2119         }
2120         list.push_back(server);
2121 }
2122
2123 // returns a list of DIRECT servernames for a specific channel
2124 void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
2125 {
2126         std::vector<char*> *ulist = c->GetUsers();
2127         unsigned int ucount = ulist->size();
2128         for (unsigned int i = 0; i < ucount; i++)
2129         {
2130                 char* o = (*ulist)[i];
2131                 userrec* otheruser = (userrec*)o;
2132                 if (otheruser->fd < 0)
2133                 {
2134                         TreeServer* best = BestRouteTo(otheruser->server);
2135                         if (best)
2136                                 AddThisServer(best,list);
2137                 }
2138         }
2139         return;
2140 }
2141
2142 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, std::string command, std::deque<std::string> &params)
2143 {
2144         TreeServer* omitroute = BestRouteTo(omit);
2145         if ((command == "NOTICE") || (command == "PRIVMSG"))
2146         {
2147                 if ((params.size() >= 2) && (*(params[0].c_str()) != '$'))
2148                 {
2149                         if (*(params[0].c_str()) != '#')
2150                         {
2151                                 // special routing for private messages/notices
2152                                 userrec* d = Srv->FindNick(params[0]);
2153                                 if (d)
2154                                 {
2155                                         std::deque<std::string> par;
2156                                         par.push_back(params[0]);
2157                                         par.push_back(":"+params[1]);
2158                                         DoOneToOne(prefix,command,par,d->server);
2159                                         return true;
2160                                 }
2161                         }
2162                         else
2163                         {
2164                                 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
2165                                 chanrec* c = Srv->FindChannel(params[0]);
2166                                 if (c)
2167                                 {
2168                                         std::deque<TreeServer*> list;
2169                                         GetListOfServersForChannel(c,list);
2170                                         log(DEBUG,"Got a list of %d servers",list.size());
2171                                         unsigned int lsize = list.size();
2172                                         for (unsigned int i = 0; i < lsize; i++)
2173                                         {
2174                                                 TreeSocket* Sock = list[i]->GetSocket();
2175                                                 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
2176                                                 {
2177                                                         log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
2178                                                         Sock->WriteLine(data);
2179                                                 }
2180                                         }
2181                                         return true;
2182                                 }
2183                         }
2184                 }
2185         }
2186         unsigned int items = TreeRoot->ChildCount();
2187         for (unsigned int x = 0; x < items; x++)
2188         {
2189                 TreeServer* Route = TreeRoot->GetChild(x);
2190                 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
2191                 {
2192                         TreeSocket* Sock = Route->GetSocket();
2193                         Sock->WriteLine(data);
2194                 }
2195         }
2196         return true;
2197 }
2198
2199 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> &params, std::string omit)
2200 {
2201         TreeServer* omitroute = BestRouteTo(omit);
2202         std::string FullLine = ":" + prefix + " " + command;
2203         unsigned int words = params.size();
2204         for (unsigned int x = 0; x < words; x++)
2205         {
2206                 FullLine = FullLine + " " + params[x];
2207         }
2208         unsigned int items = TreeRoot->ChildCount();
2209         for (unsigned int x = 0; x < items; x++)
2210         {
2211                 TreeServer* Route = TreeRoot->GetChild(x);
2212                 // Send the line IF:
2213                 // The route has a socket (its a direct connection)
2214                 // The route isnt the one to be omitted
2215                 // The route isnt the path to the one to be omitted
2216                 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
2217                 {
2218                         TreeSocket* Sock = Route->GetSocket();
2219                         Sock->WriteLine(FullLine);
2220                 }
2221         }
2222         return true;
2223 }
2224
2225 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> &params)
2226 {
2227         std::string FullLine = ":" + prefix + " " + command;
2228         unsigned int words = params.size();
2229         for (unsigned int x = 0; x < words; x++)
2230         {
2231                 FullLine = FullLine + " " + params[x];
2232         }
2233         unsigned int items = TreeRoot->ChildCount();
2234         for (unsigned int x = 0; x < items; x++)
2235         {
2236                 TreeServer* Route = TreeRoot->GetChild(x);
2237                 if (Route->GetSocket())
2238                 {
2239                         TreeSocket* Sock = Route->GetSocket();
2240                         Sock->WriteLine(FullLine);
2241                 }
2242         }
2243         return true;
2244 }
2245
2246 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> &params, std::string target)
2247 {
2248         TreeServer* Route = BestRouteTo(target);
2249         if (Route)
2250         {
2251                 std::string FullLine = ":" + prefix + " " + command;
2252                 unsigned int words = params.size();
2253                 for (unsigned int x = 0; x < words; x++)
2254                 {
2255                         FullLine = FullLine + " " + params[x];
2256                 }
2257                 if (Route->GetSocket())
2258                 {
2259                         TreeSocket* Sock = Route->GetSocket();
2260                         Sock->WriteLine(FullLine);
2261                 }
2262                 return true;
2263         }
2264         else
2265         {
2266                 return true;
2267         }
2268 }
2269
2270 std::vector<TreeSocket*> Bindings;
2271
2272 void ReadConfiguration(bool rebind)
2273 {
2274         Conf = new ConfigReader;
2275         if (rebind)
2276         {
2277                 for (int j =0; j < Conf->Enumerate("bind"); j++)
2278                 {
2279                         std::string Type = Conf->ReadValue("bind","type",j);
2280                         std::string IP = Conf->ReadValue("bind","address",j);
2281                         long Port = Conf->ReadInteger("bind","port",j,true);
2282                         if (Type == "servers")
2283                         {
2284                                 if (IP == "*")
2285                                 {
2286                                         IP = "";
2287                                 }
2288                                 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
2289                                 if (listener->GetState() == I_LISTENING)
2290                                 {
2291                                         Srv->AddSocket(listener);
2292                                         Bindings.push_back(listener);
2293                                 }
2294                                 else
2295                                 {
2296                                         log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
2297                                         listener->Close();
2298                                         delete listener;
2299                                 }
2300                         }
2301                 }
2302         }
2303         LinkBlocks.clear();
2304         for (int j =0; j < Conf->Enumerate("link"); j++)
2305         {
2306                 Link L;
2307                 L.Name = Conf->ReadValue("link","name",j);
2308                 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
2309                 L.Port = Conf->ReadInteger("link","port",j,true);
2310                 L.SendPass = Conf->ReadValue("link","sendpass",j);
2311                 L.RecvPass = Conf->ReadValue("link","recvpass",j);
2312                 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
2313                 L.EncryptionKey =  Conf->ReadValue("link","encryptionkey",j);
2314                 L.NextConnectTime = time(NULL) + L.AutoConnect;
2315                 /* Bugfix by brain, do not allow people to enter bad configurations */
2316                 if ((L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
2317                 {
2318                         LinkBlocks.push_back(L);
2319                         log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
2320                 }
2321                 else
2322                 {
2323                         log(DEFAULT,"m_spanningtree: Invalid configuration for server '%s', ignored!",L.Name.c_str());
2324                 }
2325         }
2326         delete Conf;
2327 }
2328
2329
2330 class ModuleSpanningTree : public Module
2331 {
2332         std::vector<TreeSocket*> Bindings;
2333         int line;
2334         int NumServers;
2335
2336  public:
2337
2338         ModuleSpanningTree(Server* Me)
2339                 : Module::Module(Me)
2340         {
2341                 Srv = Me;
2342                 Bindings.clear();
2343
2344                 // Create the root of the tree
2345                 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
2346
2347                 ReadConfiguration(true);
2348         }
2349
2350         void ShowLinks(TreeServer* Current, userrec* user, int hops)
2351         {
2352                 std::string Parent = TreeRoot->GetName();
2353                 if (Current->GetParent())
2354                 {
2355                         Parent = Current->GetParent()->GetName();
2356                 }
2357                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
2358                 {
2359                         ShowLinks(Current->GetChild(q),user,hops+1);
2360                 }
2361                 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
2362         }
2363
2364         int CountLocalServs()
2365         {
2366                 return TreeRoot->ChildCount();
2367         }
2368
2369         int CountServs()
2370         {
2371                 return serverlist.size();
2372         }
2373
2374         void HandleLinks(char** parameters, int pcnt, userrec* user)
2375         {
2376                 ShowLinks(TreeRoot,user,0);
2377                 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
2378                 return;
2379         }
2380
2381         void HandleLusers(char** parameters, int pcnt, userrec* user)
2382         {
2383                 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),this->CountServs());
2384                 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
2385                 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
2386                 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
2387                 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
2388                 return;
2389         }
2390
2391         // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
2392
2393         void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
2394         {
2395                 if (line < 128)
2396                 {
2397                         for (int t = 0; t < depth; t++)
2398                         {
2399                                 matrix[line][t] = ' ';
2400                         }
2401                         strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
2402                         line++;
2403                         for (unsigned int q = 0; q < Current->ChildCount(); q++)
2404                         {
2405                                 ShowMap(Current->GetChild(q),user,depth+2,matrix);
2406                         }
2407                 }
2408         }
2409
2410         // Ok, prepare to be confused.
2411         // After much mulling over how to approach this, it struck me that
2412         // the 'usual' way of doing a /MAP isnt the best way. Instead of
2413         // keeping track of a ton of ascii characters, and line by line
2414         // under recursion working out where to place them using multiplications
2415         // and divisons, we instead render the map onto a backplane of characters
2416         // (a character matrix), then draw the branches as a series of "L" shapes
2417         // from the nodes. This is not only friendlier on CPU it uses less stack.
2418
2419         void HandleMap(char** parameters, int pcnt, userrec* user)
2420         {
2421                 // This array represents a virtual screen which we will
2422                 // "scratch" draw to, as the console device of an irc
2423                 // client does not provide for a proper terminal.
2424                 char matrix[128][80];
2425                 for (unsigned int t = 0; t < 128; t++)
2426                 {
2427                         matrix[t][0] = '\0';
2428                 }
2429                 line = 0;
2430                 // The only recursive bit is called here.
2431                 ShowMap(TreeRoot,user,0,matrix);
2432                 // Process each line one by one. The algorithm has a limit of
2433                 // 128 servers (which is far more than a spanning tree should have
2434                 // anyway, so we're ok). This limit can be raised simply by making
2435                 // the character matrix deeper, 128 rows taking 10k of memory.
2436                 for (int l = 1; l < line; l++)
2437                 {
2438                         // scan across the line looking for the start of the
2439                         // servername (the recursive part of the algorithm has placed
2440                         // the servers at indented positions depending on what they
2441                         // are related to)
2442                         int first_nonspace = 0;
2443                         while (matrix[l][first_nonspace] == ' ')
2444                         {
2445                                 first_nonspace++;
2446                         }
2447                         first_nonspace--;
2448                         // Draw the `- (corner) section: this may be overwritten by
2449                         // another L shape passing along the same vertical pane, becoming
2450                         // a |- (branch) section instead.
2451                         matrix[l][first_nonspace] = '-';
2452                         matrix[l][first_nonspace-1] = '`';
2453                         int l2 = l - 1;
2454                         // Draw upwards until we hit the parent server, causing possibly
2455                         // other corners (`-) to become branches (|-)
2456                         while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
2457                         {
2458                                 matrix[l2][first_nonspace-1] = '|';
2459                                 l2--;
2460                         }
2461                 }
2462                 // dump the whole lot to the user. This is the easy bit, honest.
2463                 for (int t = 0; t < line; t++)
2464                 {
2465                         WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
2466                 }
2467                 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
2468                 return;
2469         }
2470
2471         int HandleSquit(char** parameters, int pcnt, userrec* user)
2472         {
2473                 TreeServer* s = FindServerMask(parameters[0]);
2474                 if (s)
2475                 {
2476                         if (s == TreeRoot)
2477                         {
2478                                  WriteServ(user->fd,"NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
2479                                 return 1;
2480                         }
2481                         TreeSocket* sock = s->GetSocket();
2482                         if (sock)
2483                         {
2484                                 log(DEBUG,"Splitting server %s",s->GetName().c_str());
2485                                 WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
2486                                 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
2487                                 sock->Close();
2488                         }
2489                         else
2490                         {
2491                                 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
2492                         }
2493                 }
2494                 else
2495                 {
2496                          WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
2497                 }
2498                 return 1;
2499         }
2500
2501         int HandleRemoteWhois(char** parameters, int pcnt, userrec* user)
2502         {
2503                 if ((user->fd > -1) && (pcnt > 1))
2504                 {
2505                         userrec* remote = Srv->FindNick(parameters[1]);
2506                         if ((remote) && (remote->fd < 0))
2507                         {
2508                                 std::deque<std::string> params;
2509                                 params.push_back(parameters[1]);
2510                                 DoOneToOne(user->nick,"IDLE",params,remote->server);
2511                                 return 1;
2512                         }
2513                         else if (!remote)
2514                         {
2515                                 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
2516                                 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
2517                                 return 1;
2518                         }
2519                 }
2520                 return 0;
2521         }
2522
2523         void DoPingChecks(time_t curtime)
2524         {
2525                 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
2526                 {
2527                         TreeServer* serv = TreeRoot->GetChild(j);
2528                         TreeSocket* sock = serv->GetSocket();
2529                         if (sock)
2530                         {
2531                                 if (curtime >= serv->NextPingTime())
2532                                 {
2533                                         if (serv->AnsweredLastPing())
2534                                         {
2535                                                 sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
2536                                                 serv->SetNextPingTime(curtime + 60);
2537                                         }
2538                                         else
2539                                         {
2540                                                 // they didnt answer, boot them
2541                                                 WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
2542                                                 sock->Squit(serv,"Ping timeout");
2543                                                 sock->Close();
2544                                                 return;
2545                                         }
2546                                 }
2547                         }
2548                 }
2549         }
2550
2551         void AutoConnectServers(time_t curtime)
2552         {
2553                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2554                 {
2555                         if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
2556                         {
2557                                 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
2558                                 x->NextConnectTime = curtime + x->AutoConnect;
2559                                 TreeServer* CheckDupe = FindServer(x->Name);
2560                                 if (!CheckDupe)
2561                                 {
2562                                         // an autoconnected server is not connected. Check if its time to connect it
2563                                         WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
2564                                         TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2565                                         Srv->AddSocket(newsocket);
2566                                 }
2567                         }
2568                 }
2569         }
2570
2571         int HandleVersion(char** parameters, int pcnt, userrec* user)
2572         {
2573                 // we've already checked if pcnt > 0, so this is safe
2574                 TreeServer* found = FindServerMask(parameters[0]);
2575                 if (found)
2576                 {
2577                         std::string Version = found->GetVersion();
2578                         WriteServ(user->fd,"351 %s :%s",user->nick,Version.c_str());
2579                 }
2580                 else
2581                 {
2582                         WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
2583                 }
2584                 return 1;
2585         }
2586         
2587         int HandleConnect(char** parameters, int pcnt, userrec* user)
2588         {
2589                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2590                 {
2591                         if (Srv->MatchText(x->Name.c_str(),parameters[0]))
2592                         {
2593                                 TreeServer* CheckDupe = FindServer(x->Name);
2594                                 if (!CheckDupe)
2595                                 {
2596                                         WriteServ(user->fd,"NOTICE %s :*** CONNECT: Connecting to server: \002%s\002 (%s:%d)",user->nick,x->Name.c_str(),x->IPAddr.c_str(),x->Port);
2597                                         TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2598                                         Srv->AddSocket(newsocket);
2599                                         return 1;
2600                                 }
2601                                 else
2602                                 {
2603                                         WriteServ(user->fd,"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());
2604                                         return 1;
2605                                 }
2606                         }
2607                 }
2608                 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
2609                 return 1;
2610         }
2611
2612         virtual bool HandleStats(char ** parameters, int pcnt, userrec* user)
2613         {
2614                 if (*parameters[0] == 'c')
2615                 {
2616                         for (unsigned int i = 0; i < LinkBlocks.size(); i++)
2617                         {
2618                                 WriteServ(user->fd,"213 %s C *@%s * %s %d 0 %s",user->nick,LinkBlocks[i].IPAddr.c_str(),LinkBlocks[i].Name.c_str(),LinkBlocks[i].Port,(LinkBlocks[i].EncryptionKey != "" ? "es" : " s"));
2619                                 WriteServ(user->fd,"244 %s H * * %s",user->nick,LinkBlocks[i].Name.c_str());
2620                         }
2621                         WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
2622                         WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
2623                         return true;
2624                 }
2625                 return false;
2626         }
2627
2628         virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
2629         {
2630                 if (command == "CONNECT")
2631                 {
2632                         return this->HandleConnect(parameters,pcnt,user);
2633                 }
2634                 else if (command == "SQUIT")
2635                 {
2636                         return this->HandleSquit(parameters,pcnt,user);
2637                 }
2638                 else if (command == "STATS")
2639                 {
2640                         return this->HandleStats(parameters,pcnt,user);
2641                 }
2642                 else if (command == "MAP")
2643                 {
2644                         this->HandleMap(parameters,pcnt,user);
2645                         return 1;
2646                 }
2647                 else if (command == "LUSERS")
2648                 {
2649                         this->HandleLusers(parameters,pcnt,user);
2650                         return 1;
2651                 }
2652                 else if (command == "LINKS")
2653                 {
2654                         this->HandleLinks(parameters,pcnt,user);
2655                         return 1;
2656                 }
2657                 else if (command == "WHOIS")
2658                 {
2659                         if (pcnt > 1)
2660                         {
2661                                 // remote whois
2662                                 return this->HandleRemoteWhois(parameters,pcnt,user);
2663                         }
2664                 }
2665                 else if ((command == "VERSION") && (pcnt > 0))
2666                 {
2667                         this->HandleVersion(parameters,pcnt,user);
2668                         return 1;
2669                 }
2670                 else if (Srv->IsValidModuleCommand(command, pcnt, user))
2671                 {
2672                         // this bit of code cleverly routes all module commands
2673                         // to all remote severs *automatically* so that modules
2674                         // can just handle commands locally, without having
2675                         // to have any special provision in place for remote
2676                         // commands and linking protocols.
2677                         std::deque<std::string> params;
2678                         params.clear();
2679                         for (int j = 0; j < pcnt; j++)
2680                         {
2681                                 if (strchr(parameters[j],' '))
2682                                 {
2683                                         params.push_back(":" + std::string(parameters[j]));
2684                                 }
2685                                 else
2686                                 {
2687                                         params.push_back(std::string(parameters[j]));
2688                                 }
2689                         }
2690                         DoOneToMany(user->nick,command,params);
2691                 }
2692                 return 0;
2693         }
2694
2695         virtual void OnGetServerDescription(std::string servername,std::string &description)
2696         {
2697                 TreeServer* s = FindServer(servername);
2698                 if (s)
2699                 {
2700                         description = s->GetDesc();
2701                 }
2702         }
2703
2704         virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
2705         {
2706                 if (source->fd > -1)
2707                 {
2708                         std::deque<std::string> params;
2709                         params.push_back(dest->nick);
2710                         params.push_back(channel->name);
2711                         DoOneToMany(source->nick,"INVITE",params);
2712                 }
2713         }
2714
2715         virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
2716         {
2717                 std::deque<std::string> params;
2718                 params.push_back(chan->name);
2719                 params.push_back(":"+topic);
2720                 DoOneToMany(user->nick,"TOPIC",params);
2721         }
2722
2723         virtual void OnWallops(userrec* user, std::string text)
2724         {
2725                 if (user->fd > -1)
2726                 {
2727                         std::deque<std::string> params;
2728                         params.push_back(":"+text);
2729                         DoOneToMany(user->nick,"WALLOPS",params);
2730                 }
2731         }
2732
2733         virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
2734         {
2735                 if (target_type == TYPE_USER)
2736                 {
2737                         userrec* d = (userrec*)dest;
2738                         if ((d->fd < 0) && (user->fd > -1))
2739                         {
2740                                 std::deque<std::string> params;
2741                                 params.clear();
2742                                 params.push_back(d->nick);
2743                                 params.push_back(":"+text);
2744                                 DoOneToOne(user->nick,"NOTICE",params,d->server);
2745                         }
2746                 }
2747                 else
2748                 {
2749                         if (user->fd > -1)
2750                         {
2751                                 chanrec *c = (chanrec*)dest;
2752                                 std::deque<TreeServer*> list;
2753                                 GetListOfServersForChannel(c,list);
2754                                 unsigned int ucount = list.size();
2755                                 for (unsigned int i = 0; i < ucount; i++)
2756                                 {
2757                                         TreeSocket* Sock = list[i]->GetSocket();
2758                                         if (Sock)
2759                                                 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+std::string(c->name)+" :"+text);
2760                                 }
2761                         }
2762                 }
2763         }
2764
2765         virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
2766         {
2767                 if (target_type == TYPE_USER)
2768                 {
2769                         // route private messages which are targetted at clients only to the server
2770                         // which needs to receive them
2771                         userrec* d = (userrec*)dest;
2772                         if ((d->fd < 0) && (user->fd > -1))
2773                         {
2774                                 std::deque<std::string> params;
2775                                 params.clear();
2776                                 params.push_back(d->nick);
2777                                 params.push_back(":"+text);
2778                                 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
2779                         }
2780                 }
2781                 else
2782                 {
2783                         if (user->fd > -1)
2784                         {
2785                                 chanrec *c = (chanrec*)dest;
2786                                 std::deque<TreeServer*> list;
2787                                 GetListOfServersForChannel(c,list);
2788                                 unsigned int ucount = list.size();
2789                                 for (unsigned int i = 0; i < ucount; i++)
2790                                 {
2791                                         TreeSocket* Sock = list[i]->GetSocket();
2792                                         if (Sock)
2793                                                 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+std::string(c->name)+" :"+text);
2794                                 }
2795                         }
2796                 }
2797         }
2798
2799         virtual void OnBackgroundTimer(time_t curtime)
2800         {
2801                 AutoConnectServers(curtime);
2802                 DoPingChecks(curtime);
2803         }
2804
2805         virtual void OnUserJoin(userrec* user, chanrec* channel)
2806         {
2807                 // Only do this for local users
2808                 if (user->fd > -1)
2809                 {
2810                         std::deque<std::string> params;
2811                         params.clear();
2812                         params.push_back(channel->name);
2813                         if (*channel->key)
2814                         {
2815                                 // if the channel has a key, force the join by emulating the key.
2816                                 params.push_back(channel->key);
2817                         }
2818                         if (channel->GetUserCounter() > 1)
2819                         {
2820                                 // not the first in the channel
2821                                 DoOneToMany(user->nick,"JOIN",params);
2822                         }
2823                         else
2824                         {
2825                                 // first in the channel, set up their permissions
2826                                 // and the channel TS with FJOIN.
2827                                 char ts[24];
2828                                 snprintf(ts,24,"%lu",(unsigned long)channel->age);
2829                                 params.clear();
2830                                 params.push_back(channel->name);
2831                                 params.push_back(ts);
2832                                 params.push_back("@"+std::string(user->nick));
2833                                 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
2834                         }
2835                 }
2836         }
2837
2838         virtual void OnChangeHost(userrec* user, std::string newhost)
2839         {
2840                 // only occurs for local clients
2841                 if (user->registered != 7)
2842                         return;
2843                 std::deque<std::string> params;
2844                 params.push_back(newhost);
2845                 DoOneToMany(user->nick,"FHOST",params);
2846         }
2847
2848         virtual void OnChangeName(userrec* user, std::string gecos)
2849         {
2850                 // only occurs for local clients
2851                 if (user->registered != 7)
2852                         return;
2853                 std::deque<std::string> params;
2854                 params.push_back(gecos);
2855                 DoOneToMany(user->nick,"FNAME",params);
2856         }
2857
2858         virtual void OnUserPart(userrec* user, chanrec* channel)
2859         {
2860                 if (user->fd > -1)
2861                 {
2862                         std::deque<std::string> params;
2863                         params.push_back(channel->name);
2864                         DoOneToMany(user->nick,"PART",params);
2865                 }
2866         }
2867
2868         virtual void OnUserConnect(userrec* user)
2869         {
2870                 char agestr[MAXBUF];
2871                 if (user->fd > -1)
2872                 {
2873                         std::deque<std::string> params;
2874                         snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
2875                         params.push_back(agestr);
2876                         params.push_back(user->nick);
2877                         params.push_back(user->host);
2878                         params.push_back(user->dhost);
2879                         params.push_back(user->ident);
2880                         params.push_back("+"+std::string(user->modes));
2881                         params.push_back(user->ip);
2882                         params.push_back(":"+std::string(user->fullname));
2883                         DoOneToMany(Srv->GetServerName(),"NICK",params);
2884                 }
2885         }
2886
2887         virtual void OnUserQuit(userrec* user, std::string reason)
2888         {
2889                 if ((user->fd > -1) && (user->registered == 7))
2890                 {
2891                         std::deque<std::string> params;
2892                         params.push_back(":"+reason);
2893                         DoOneToMany(user->nick,"QUIT",params);
2894                 }
2895         }
2896
2897         virtual void OnUserPostNick(userrec* user, std::string oldnick)
2898         {
2899                 if (user->fd > -1)
2900                 {
2901                         std::deque<std::string> params;
2902                         params.push_back(user->nick);
2903                         DoOneToMany(oldnick,"NICK",params);
2904                 }
2905         }
2906
2907         virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
2908         {
2909                 if (source->fd > -1)
2910                 {
2911                         std::deque<std::string> params;
2912                         params.push_back(chan->name);
2913                         params.push_back(user->nick);
2914                         params.push_back(":"+reason);
2915                         DoOneToMany(source->nick,"KICK",params);
2916                 }
2917         }
2918
2919         virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
2920         {
2921                 std::deque<std::string> params;
2922                 params.push_back(dest->nick);
2923                 params.push_back(":"+reason);
2924                 DoOneToMany(source->nick,"KILL",params);
2925         }
2926
2927         virtual void OnRehash(std::string parameter)
2928         {
2929                 if (parameter != "")
2930                 {
2931                         std::deque<std::string> params;
2932                         params.push_back(parameter);
2933                         DoOneToMany(Srv->GetServerName(),"REHASH",params);
2934                         // check for self
2935                         if (Srv->MatchText(Srv->GetServerName(),parameter))
2936                         {
2937                                 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
2938                                 Srv->RehashServer();
2939                         }
2940                 }
2941                 ReadConfiguration(false);
2942         }
2943
2944         // note: the protocol does not allow direct umode +o except
2945         // via NICK with 8 params. sending OPERTYPE infers +o modechange
2946         // locally.
2947         virtual void OnOper(userrec* user, std::string opertype)
2948         {
2949                 if (user->fd > -1)
2950                 {
2951                         std::deque<std::string> params;
2952                         params.push_back(opertype);
2953                         DoOneToMany(user->nick,"OPERTYPE",params);
2954                 }
2955         }
2956
2957         void OnLine(userrec* source, std::string host, bool adding, char linetype, long duration, std::string reason)
2958         {
2959                 if (source->fd > -1)
2960                 {
2961                         char type[8];
2962                         snprintf(type,8,"%cLINE",linetype);
2963                         std::string stype = type;
2964                         if (adding)
2965                         {
2966                                 char sduration[MAXBUF];
2967                                 snprintf(sduration,MAXBUF,"%ld",duration);
2968                                 std::deque<std::string> params;
2969                                 params.push_back(host);
2970                                 params.push_back(sduration);
2971                                 params.push_back(":"+reason);
2972                                 DoOneToMany(source->nick,stype,params);
2973                         }
2974                         else
2975                         {
2976                                 std::deque<std::string> params;
2977                                 params.push_back(host);
2978                                 DoOneToMany(source->nick,stype,params);
2979                         }
2980                 }
2981         }
2982
2983         virtual void OnAddGLine(long duration, userrec* source, std::string reason, std::string hostmask)
2984         {
2985                 OnLine(source,hostmask,true,'G',duration,reason);
2986         }
2987         
2988         virtual void OnAddZLine(long duration, userrec* source, std::string reason, std::string ipmask)
2989         {
2990                 OnLine(source,ipmask,true,'Z',duration,reason);
2991         }
2992
2993         virtual void OnAddQLine(long duration, userrec* source, std::string reason, std::string nickmask)
2994         {
2995                 OnLine(source,nickmask,true,'Q',duration,reason);
2996         }
2997
2998         virtual void OnAddELine(long duration, userrec* source, std::string reason, std::string hostmask)
2999         {
3000                 OnLine(source,hostmask,true,'E',duration,reason);
3001         }
3002
3003         virtual void OnDelGLine(userrec* source, std::string hostmask)
3004         {
3005                 OnLine(source,hostmask,false,'G',0,"");
3006         }
3007
3008         virtual void OnDelZLine(userrec* source, std::string ipmask)
3009         {
3010                 OnLine(source,ipmask,false,'Z',0,"");
3011         }
3012
3013         virtual void OnDelQLine(userrec* source, std::string nickmask)
3014         {
3015                 OnLine(source,nickmask,false,'Q',0,"");
3016         }
3017
3018         virtual void OnDelELine(userrec* source, std::string hostmask)
3019         {
3020                 OnLine(source,hostmask,false,'E',0,"");
3021         }
3022
3023         virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
3024         {
3025                 if ((user->fd > -1) && (user->registered == 7))
3026                 {
3027                         if (target_type == TYPE_USER)
3028                         {
3029                                 userrec* u = (userrec*)dest;
3030                                 std::deque<std::string> params;
3031                                 params.push_back(u->nick);
3032                                 params.push_back(text);
3033                                 DoOneToMany(user->nick,"MODE",params);
3034                         }
3035                         else
3036                         {
3037                                 chanrec* c = (chanrec*)dest;
3038                                 std::deque<std::string> params;
3039                                 params.push_back(c->name);
3040                                 params.push_back(text);
3041                                 DoOneToMany(user->nick,"MODE",params);
3042                         }
3043                 }
3044         }
3045
3046         virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
3047         {
3048                 TreeSocket* s = (TreeSocket*)opaque;
3049                 if (target)
3050                 {
3051                         if (target_type == TYPE_USER)
3052                         {
3053                                 userrec* u = (userrec*)target;
3054                                 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
3055                         }
3056                         else
3057                         {
3058                                 chanrec* c = (chanrec*)target;
3059                                 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
3060                         }
3061                 }
3062         }
3063
3064         virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, std::string extname, std::string extdata)
3065         {
3066                 TreeSocket* s = (TreeSocket*)opaque;
3067                 if (target)
3068                 {
3069                         if (target_type == TYPE_USER)
3070                         {
3071                                 userrec* u = (userrec*)target;
3072                                 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+u->nick+" "+extname+" :"+extdata);
3073                         }
3074                         else
3075                         {
3076                                 chanrec* c = (chanrec*)target;
3077                                 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+c->name+" "+extname+" :"+extdata);
3078                         }
3079                 }
3080         }
3081
3082         virtual ~ModuleSpanningTree()
3083         {
3084         }
3085
3086         virtual Version GetVersion()
3087         {
3088                 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
3089         }
3090 };
3091
3092
3093 class ModuleSpanningTreeFactory : public ModuleFactory
3094 {
3095  public:
3096         ModuleSpanningTreeFactory()
3097         {
3098         }
3099         
3100         ~ModuleSpanningTreeFactory()
3101         {
3102         }
3103         
3104         virtual Module * CreateModule(Server* Me)
3105         {
3106                 TreeProtocolModule = new ModuleSpanningTree(Me);
3107                 return TreeProtocolModule;
3108         }
3109         
3110 };
3111
3112
3113 extern "C" void * init_module( void )
3114 {
3115         return new ModuleSpanningTreeFactory;
3116 }