]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree.cpp
Added more verbose error output during link
[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                         std::string quitserver = this->myhost;
718                         if (this->InboundServerName != "")
719                         {
720                                 quitserver = this->InboundServerName;
721                         }
722                         WriteOpers("*** \2ERROR\2: Server '%s' does not have the same set of modules loaded, cannot link!",quitserver.c_str());
723                         WriteOpers("*** Our networked module set is: '%s'",this->MyCapabilities().c_str());
724                         WriteOpers("*** Other server's networked module set is: '%s'",params[0].c_str());
725                         WriteOpers("*** These lists must match exactly on both servers. Please correct these errors, and try again.");
726                         this->WriteLine("ERROR :CAPAB mismatch; My capabilities: '"+this->MyCapabilities()+"'");
727                         return false;
728                 }
729                 return true;
730         }
731
732         /* This function forces this server to quit, removing this server
733          * and any users on it (and servers and users below that, etc etc).
734          * It's very slow and pretty clunky, but luckily unless your network
735          * is having a REAL bad hair day, this function shouldnt be called
736          * too many times a month ;-)
737          */
738         void SquitServer(TreeServer* Current, CullList* Goners)
739         {
740                 /* recursively squit the servers attached to 'Current'.
741                  * We're going backwards so we don't remove users
742                  * while we still need them ;)
743                  */
744                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
745                 {
746                         TreeServer* recursive_server = Current->GetChild(q);
747                         this->SquitServer(recursive_server,Goners);
748                 }
749                 /* Now we've whacked the kids, whack self */
750                 num_lost_servers++;
751                 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
752                 {
753                         if (!strcasecmp(u->second->server,Current->GetName().c_str()))
754                         {
755                                 std::string qreason = Current->GetName()+" "+std::string(Srv->GetServerName());
756                                 Goners->AddItem(u->second,qreason);
757                                 num_lost_users++;
758                         }
759                 }
760         }
761
762         /* This is a wrapper function for SquitServer above, which
763          * does some validation first and passes on the SQUIT to all
764          * other remaining servers.
765          */
766         void Squit(TreeServer* Current,std::string reason)
767         {
768                 if ((Current) && (Current != TreeRoot))
769                 {
770                         std::deque<std::string> params;
771                         params.push_back(Current->GetName());
772                         params.push_back(":"+reason);
773                         DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
774                         if (Current->GetParent() == TreeRoot)
775                         {
776                                 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
777                         }
778                         else
779                         {
780                                 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
781                         }
782                         num_lost_servers = 0;
783                         num_lost_users = 0;
784                         CullList* Goners = new CullList();
785                         SquitServer(Current, Goners);
786                         Goners->Apply();
787                         Current->Tidy();
788                         Current->GetParent()->DelChild(Current);
789                         delete Current;
790                         delete Goners;
791                         WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
792                 }
793                 else
794                 {
795                         log(DEFAULT,"Squit from unknown server");
796                 }
797         }
798
799         /* FMODE command */
800         bool ForceMode(std::string source, std::deque<std::string> params)
801         {
802                 userrec* who = new userrec;
803                 who->fd = FD_MAGIC_NUMBER;
804                 if (params.size() < 2)
805                         return true;
806                 char* modelist[255];
807                 for (unsigned int q = 0; q < params.size(); q++)
808                 {
809                         modelist[q] = (char*)params[q].c_str();
810                 }
811                 Srv->SendMode(modelist,params.size(),who);
812                 DoOneToAllButSender(source,"FMODE",params,source);
813                 delete who;
814                 return true;
815         }
816
817         /* FTOPIC command */
818         bool ForceTopic(std::string source, std::deque<std::string> params)
819         {
820                 if (params.size() != 4)
821                         return true;
822                 std::string channel = params[0];
823                 time_t ts = atoi(params[1].c_str());
824                 std::string setby = params[2];
825                 std::string topic = params[3];
826
827                 chanrec* c = Srv->FindChannel(channel);
828                 if (c)
829                 {
830                         if ((ts >= c->topicset) || (!*c->topic))
831                         {
832                                 std::string oldtopic = c->topic;
833                                 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
834                                 strlcpy(c->setby,setby.c_str(),NICKMAX);
835                                 c->topicset = ts;
836                                 /* if the topic text is the same as the current topic,
837                                  * dont bother to send the TOPIC command out, just silently
838                                  * update the set time and set nick.
839                                  */
840                                 if (oldtopic != topic)
841                                         WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
842                         }
843                         
844                 }
845                 
846                 /* all done, send it on its way */
847                 params[3] = ":" + params[3];
848                 DoOneToAllButSender(source,"FTOPIC",params,source);
849
850                 return true;
851         }
852
853         /* FJOIN, similar to unreal SJOIN */
854         bool ForceJoin(std::string source, std::deque<std::string> params)
855         {
856                 if (params.size() < 3)
857                         return true;
858
859                 char first[MAXBUF];
860                 char modestring[MAXBUF];
861                 char* mode_users[127];
862                 mode_users[0] = first;
863                 mode_users[1] = modestring;
864                 strcpy(mode_users[1],"+");
865                 unsigned int modectr = 2;
866                 
867                 userrec* who = NULL;
868                 std::string channel = params[0];
869                 time_t TS = atoi(params[1].c_str());
870                 char* key = "";
871                 
872                 chanrec* chan = Srv->FindChannel(channel);
873                 if (chan)
874                 {
875                         key = chan->key;
876                 }
877                 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
878
879                 /* default is a high value, which if we dont have this
880                  * channel will let the other side apply their modes.
881                  */
882                 time_t ourTS = time(NULL)+600;
883                 chanrec* us = Srv->FindChannel(channel);
884                 if (us)
885                 {
886                         ourTS = us->age;
887                 }
888
889                 log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
890
891                 /* do this first, so our mode reversals are correctly received by other servers
892                  * if there is a TS collision.
893                  */
894                 DoOneToAllButSender(source,"FJOIN",params,source);
895                 
896                 for (unsigned int usernum = 2; usernum < params.size(); usernum++)
897                 {
898                         /* process one channel at a time, applying modes. */
899                         char* usr = (char*)params[usernum].c_str();
900                         char permissions = *usr;
901                         switch (permissions)
902                         {
903                                 case '@':
904                                         usr++;
905                                         mode_users[modectr++] = usr;
906                                         strlcat(modestring,"o",MAXBUF);
907                                 break;
908                                 case '%':
909                                         usr++;
910                                         mode_users[modectr++] = usr;
911                                         strlcat(modestring,"h",MAXBUF);
912                                 break;
913                                 case '+':
914                                         usr++;
915                                         mode_users[modectr++] = usr;
916                                         strlcat(modestring,"v",MAXBUF);
917                                 break;
918                         }
919                         who = Srv->FindNick(usr);
920                         if (who)
921                         {
922                                 Srv->JoinUserToChannel(who,channel,key);
923                                 if (modectr >= (MAXMODES-1))
924                                 {
925                                         /* theres a mode for this user. push them onto the mode queue, and flush it
926                                          * if there are more than MAXMODES to go.
927                                          */
928                                         if ((ourTS >= TS) || (Srv->IsUlined(who->server)))
929                                         {
930                                                 /* We also always let u-lined clients win, no matter what the TS value */
931                                                 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
932                                                 Srv->SendMode(mode_users,modectr,who);
933                                         }
934                                         else
935                                         {
936                                                 log(DEBUG,"Their channel newer than ours, bouncing their modes");
937                                                 /* bouncy bouncy! */
938                                                 std::deque<std::string> params;
939                                                 /* modes are now being UNSET... */
940                                                 *mode_users[1] = '-';
941                                                 for (unsigned int x = 0; x < modectr; x++)
942                                                 {
943                                                         params.push_back(mode_users[x]);
944                                                 }
945                                                 // tell everyone to bounce the modes. bad modes, bad!
946                                                 DoOneToMany(Srv->GetServerName(),"FMODE",params);
947                                         }
948                                         strcpy(mode_users[1],"+");
949                                         modectr = 2;
950                                 }
951                         }
952                 }
953                 /* there werent enough modes built up to flush it during FJOIN,
954                  * or, there are a number left over. flush them out.
955                  */
956                 if ((modectr > 2) && (who))
957                 {
958                         if (ourTS >= TS)
959                         {
960                                 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
961                                 Srv->SendMode(mode_users,modectr,who);
962                         }
963                         else
964                         {
965                                 log(DEBUG,"Their channel newer than ours, bouncing their modes");
966                                 std::deque<std::string> params;
967                                 *mode_users[1] = '-';
968                                 for (unsigned int x = 0; x < modectr; x++)
969                                 {
970                                         params.push_back(mode_users[x]);
971                                 }
972                                 DoOneToMany(Srv->GetServerName(),"FMODE",params);
973                         }
974                 }
975                 return true;
976         }
977
978         /* NICK command */
979         bool IntroduceClient(std::string source, std::deque<std::string> params)
980         {
981                 if (params.size() < 8)
982                         return true;
983                 // NICK age nick host dhost ident +modes ip :gecos
984                 //       0   1    2    3      4     5    6   7
985                 std::string nick = params[1];
986                 std::string host = params[2];
987                 std::string dhost = params[3];
988                 std::string ident = params[4];
989                 time_t age = atoi(params[0].c_str());
990                 std::string modes = params[5];
991                 while (*(modes.c_str()) == '+')
992                 {
993                         char* m = (char*)modes.c_str();
994                         m++;
995                         modes = m;
996                 }
997                 std::string ip = params[6];
998                 std::string gecos = params[7];
999                 char* tempnick = (char*)nick.c_str();
1000                 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
1001                 
1002                 user_hash::iterator iter;
1003                 iter = clientlist.find(tempnick);
1004                 if (iter != clientlist.end())
1005                 {
1006                         // nick collision
1007                         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);
1008                         this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
1009                         return true;
1010                 }
1011
1012                 clientlist[tempnick] = new userrec();
1013                 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
1014                 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
1015                 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
1016                 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
1017                 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
1018                 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
1019                 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
1020                 clientlist[tempnick]->registered = 7;
1021                 clientlist[tempnick]->signon = age;
1022                 strlcpy(clientlist[tempnick]->modes, modes.c_str(),53);
1023                 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
1024
1025                 ucrec a;
1026                 a.channel = NULL;
1027                 a.uc_modes = 0;
1028                 for (int i = 0; i < MAXCHANS; i++)
1029                         clientlist[tempnick]->chans.push_back(a);
1030
1031                 if (!this->bursting)
1032                 {
1033                         WriteOpers("*** Client connecting at %s: %s!%s@%s [%s]",clientlist[tempnick]->server,clientlist[tempnick]->nick,clientlist[tempnick]->ident,clientlist[tempnick]->host,clientlist[tempnick]->ip);
1034                 }
1035                 params[7] = ":" + params[7];
1036                 DoOneToAllButSender(source,"NICK",params,source);
1037                 return true;
1038         }
1039
1040         /* Send one or more FJOINs for a channel of users.
1041          * If the length of a single line is more than 480-NICKMAX
1042          * in length, it is split over multiple lines.
1043          */
1044         void SendFJoins(TreeServer* Current, chanrec* c)
1045         {
1046                 log(DEBUG,"Sending FJOINs to other server for %s",c->name);
1047                 char list[MAXBUF];
1048                 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1049                 std::vector<char*> *ulist = c->GetUsers();
1050                 for (unsigned int i = 0; i < ulist->size(); i++)
1051                 {
1052                         char* o = (*ulist)[i];
1053                         userrec* otheruser = (userrec*)o;
1054                         strlcat(list," ",MAXBUF);
1055                         strlcat(list,cmode(otheruser,c),MAXBUF);
1056                         strlcat(list,otheruser->nick,MAXBUF);
1057                         if (strlen(list)>(480-NICKMAX))
1058                         {
1059                                 log(DEBUG,"FJOIN line wrapped");
1060                                 this->WriteLine(list);
1061                                 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1062                         }
1063                 }
1064                 if (list[strlen(list)-1] != ':')
1065                 {
1066                         log(DEBUG,"Final FJOIN line");
1067                         this->WriteLine(list);
1068                 }
1069         }
1070
1071         /* Send G, Q, Z and E lines */
1072         void SendXLines(TreeServer* Current)
1073         {
1074                 char data[MAXBUF];
1075                 /* Yes, these arent too nice looking, but they get the job done */
1076                 for (std::vector<ZLine>::iterator i = zlines.begin(); i != zlines.end(); i++)
1077                 {
1078                         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);
1079                         this->WriteLine(data);
1080                 }
1081                 for (std::vector<QLine>::iterator i = qlines.begin(); i != qlines.end(); i++)
1082                 {
1083                         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);
1084                         this->WriteLine(data);
1085                 }
1086                 for (std::vector<GLine>::iterator i = glines.begin(); i != glines.end(); i++)
1087                 {
1088                         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);
1089                         this->WriteLine(data);
1090                 }
1091                 for (std::vector<ELine>::iterator i = elines.begin(); i != elines.end(); i++)
1092                 {
1093                         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);
1094                         this->WriteLine(data);
1095                 }
1096                 for (std::vector<ZLine>::iterator i = pzlines.begin(); i != pzlines.end(); i++)
1097                 {
1098                         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);
1099                         this->WriteLine(data);
1100                 }
1101                 for (std::vector<QLine>::iterator i = pqlines.begin(); i != pqlines.end(); i++)
1102                 {
1103                         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);
1104                         this->WriteLine(data);
1105                 }
1106                 for (std::vector<GLine>::iterator i = pglines.begin(); i != pglines.end(); i++)
1107                 {
1108                         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);
1109                         this->WriteLine(data);
1110                 }
1111                 for (std::vector<ELine>::iterator i = pelines.begin(); i != pelines.end(); i++)
1112                 {
1113                         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);
1114                         this->WriteLine(data);
1115                 }
1116         }
1117
1118         /* Send channel modes and topics */
1119         void SendChannelModes(TreeServer* Current)
1120         {
1121                 char data[MAXBUF];
1122                 std::deque<std::string> list;
1123                 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
1124                 {
1125                         SendFJoins(Current, c->second);
1126                         snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
1127                         this->WriteLine(data);
1128                         if (*c->second->topic)
1129                         {
1130                                 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);
1131                                 this->WriteLine(data);
1132                         }
1133                         for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
1134                         {
1135                                 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
1136                                 this->WriteLine(data);
1137                         }
1138                         FOREACH_MOD OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this);
1139                         list.clear();
1140                         c->second->GetExtList(list);
1141                         for (unsigned int j = 0; j < list.size(); j++)
1142                         {
1143                                 FOREACH_MOD OnSyncChannelMetaData(c->second,(Module*)TreeProtocolModule,(void*)this,list[j]);
1144                         }
1145                 }
1146         }
1147
1148         /* send all users and their oper state/modes */
1149         void SendUsers(TreeServer* Current)
1150         {
1151                 char data[MAXBUF];
1152                 std::deque<std::string> list;
1153                 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
1154                 {
1155                         if (u->second->registered == 7)
1156                         {
1157                                 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);
1158                                 this->WriteLine(data);
1159                                 if (strchr(u->second->modes,'o'))
1160                                 {
1161                                         this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
1162                                 }
1163                                 FOREACH_MOD OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this);
1164                                 list.clear();
1165                                 u->second->GetExtList(list);
1166                                 for (unsigned int j = 0; j < list.size(); j++)
1167                                 {
1168                                         FOREACH_MOD OnSyncUserMetaData(u->second,(Module*)TreeProtocolModule,(void*)this,list[j]);
1169                                 }
1170                         }
1171                 }
1172         }
1173
1174         /* This function is called when we want to send a netburst to a local
1175          * server. There is a set order we must do this, because for example
1176          * users require their servers to exist, and channels require their
1177          * users to exist. You get the idea.
1178          */
1179         void DoBurst(TreeServer* s)
1180         {
1181                 Srv->SendOpers("*** Bursting to \2"+s->GetName()+"\2.");
1182                 this->WriteLine("BURST");
1183                 /* send our version string */
1184                 this->WriteLine(":"+Srv->GetServerName()+" VERSION :"+Srv->GetVersion());
1185                 /* Send server tree */
1186                 this->SendServers(TreeRoot,s,1);
1187                 /* Send users and their oper status */
1188                 this->SendUsers(s);
1189                 /* Send everything else (channel modes, xlines etc) */
1190                 this->SendChannelModes(s);
1191                 this->SendXLines(s);
1192                 this->WriteLine("ENDBURST");
1193                 Srv->SendOpers("*** Finished bursting to \2"+s->GetName()+"\2.");
1194         }
1195
1196         /* This function is called when we receive data from a remote
1197          * server. We buffer the data in a std::string (it doesnt stay
1198          * there for long), reading using InspSocket::Read() which can
1199          * read up to 16 kilobytes in one operation.
1200          *
1201          * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
1202          * THE SOCKET OBJECT FOR US.
1203          */
1204         virtual bool OnDataReady()
1205         {
1206                 char* data = this->Read();
1207                 if (data)
1208                 {
1209                         this->in_buffer += data;
1210                         /* While there is at least one new line in the buffer,
1211                          * do something useful (we hope!) with it.
1212                          */
1213                         while (in_buffer.find("\n") != std::string::npos)
1214                         {
1215                                 char* line = (char*)in_buffer.c_str();
1216                                 std::string ret = "";
1217                                 while ((*line != '\n') && (strlen(line)))
1218                                 {
1219                                         ret = ret + *line;
1220                                         line++;
1221                                 }
1222                                 if ((*line == '\n') || (*line == '\r'))
1223                                         line++;
1224                                 in_buffer = line;
1225                                 /* Process this one, abort if it
1226                                  * didnt return true.
1227                                  */
1228                                 if (this->ctx)
1229                                 {
1230                                         char out[1024];
1231                                         char result[1024];
1232                                         log(DEBUG,"Original string '%s'",ret.c_str());
1233                                         /* ERROR is still allowed unencryped */
1234                                         if (ret.substr(0,7) != "ERROR :")
1235                                         {
1236                                                 int nbytes = from64tobits(out, ret.c_str(), 1024);
1237                                                 log(DEBUG,"m_spanningtree: decrypt %d bytes",nbytes);
1238                                                 ctx->Decrypt(out, result, nbytes, 0);
1239                                                 for (int t = 0; t < nbytes; t++)
1240                                                         if (result[t] == '\7') result[t] = 0;
1241                                                 ret = result;
1242                                         }
1243                                 }
1244                                 if (!this->ProcessLine(ret))
1245                                 {
1246                                         return false;
1247                                 }
1248                         }
1249                 }
1250                 return (data != NULL);
1251         }
1252
1253         int WriteLine(std::string line)
1254         {
1255                 log(DEBUG,"OUT: %s",line.c_str());
1256                 if (this->ctx)
1257                 {
1258                         log(DEBUG,"AES context");
1259                         char result[1024];
1260                         char result64[1024];
1261                         if (this->keylength)
1262                         {
1263                                 while (line.length() % this->keylength != 0)
1264                                 {
1265                                         // pad it to be a multiple of the key length
1266                                         line = line + "\7";
1267                                 }
1268                         }
1269                         ctx->Encrypt(line.c_str(), result, line.length(),0);
1270                         to64frombits((unsigned char*)result64,
1271                                         (unsigned char*)result,
1272                                         line.length());
1273                         line = result64;
1274                         log(DEBUG,"Encrypted: %s",line.c_str());
1275                         //int from64tobits(char *out, const char *in, int maxlen);
1276                 }
1277                 return this->Write(line + "\r\n");
1278         }
1279
1280         /* Handle ERROR command */
1281         bool Error(std::deque<std::string> params)
1282         {
1283                 if (params.size() < 1)
1284                         return false;
1285                 std::string Errmsg = params[0];
1286                 std::string SName = myhost;
1287                 if (InboundServerName != "")
1288                 {
1289                         SName = InboundServerName;
1290                 }
1291                 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
1292                 /* we will return false to cause the socket to close.
1293                  */
1294                 return false;
1295         }
1296
1297         /* Because the core won't let users or even SERVERS set +o,
1298          * we use the OPERTYPE command to do this.
1299          */
1300         bool OperType(std::string prefix, std::deque<std::string> &params)
1301         {
1302                 if (params.size() != 1)
1303                         return true;
1304                 std::string opertype = params[0];
1305                 userrec* u = Srv->FindNick(prefix);
1306                 if (u)
1307                 {
1308                         strlcpy(u->oper,opertype.c_str(),NICKMAX);
1309                         if (!strchr(u->modes,'o'))
1310                         {
1311                                 strcat(u->modes,"o");
1312                         }
1313                         DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
1314                 }
1315                 return true;
1316         }
1317
1318         /* Because Andy insists that services-compatible servers must
1319          * implement SVSNICK and SVSJOIN, that's exactly what we do :p
1320          */
1321         bool ForceNick(std::string prefix, std::deque<std::string> &params)
1322         {
1323                 if (params.size() < 3)
1324                         return true;
1325                 userrec* u = Srv->FindNick(params[0]);
1326                 if (u)
1327                 {
1328                         Srv->ChangeUserNick(u,params[1]);
1329                         u->age = atoi(params[2].c_str());
1330                         DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
1331                 }
1332                 return true;
1333         }
1334
1335         bool ServiceJoin(std::string prefix, std::deque<std::string> &params)
1336         {
1337                 if (params.size() < 2)
1338                         return true;
1339                 userrec* u = Srv->FindNick(params[0]);
1340                 if (u)
1341                 {
1342                         Srv->JoinUserToChannel(u,params[1],"");
1343                         DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
1344                 }
1345                 return true;
1346         }
1347
1348         bool RemoteRehash(std::string prefix, std::deque<std::string> &params)
1349         {
1350                 if (params.size() < 1)
1351                         return false;
1352                 std::string servermask = params[0];
1353                 if (Srv->MatchText(Srv->GetServerName(),servermask))
1354                 {
1355                         Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
1356                         Srv->RehashServer();
1357                         ReadConfiguration(false);
1358                 }
1359                 DoOneToAllButSender(prefix,"REHASH",params,prefix);
1360                 return true;
1361         }
1362
1363         bool RemoteKill(std::string prefix, std::deque<std::string> &params)
1364         {
1365                 if (params.size() != 2)
1366                         return true;
1367                 std::string nick = params[0];
1368                 userrec* u = Srv->FindNick(prefix);
1369                 userrec* who = Srv->FindNick(nick);
1370                 if (who)
1371                 {
1372                         /* Prepend kill source, if we don't have one */
1373                         std::string sourceserv = prefix;
1374                         if (u)
1375                         {
1376                                 sourceserv = u->server;
1377                         }
1378                         if (*(params[1].c_str()) != '[')
1379                         {
1380                                 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
1381                         }
1382                         std::string reason = params[1];
1383                         params[1] = ":" + params[1];
1384                         DoOneToAllButSender(prefix,"KILL",params,sourceserv);
1385                         Srv->QuitUser(who,reason);
1386                 }
1387                 return true;
1388         }
1389
1390         bool LocalPong(std::string prefix, std::deque<std::string> &params)
1391         {
1392                 if (params.size() < 1)
1393                         return true;
1394                 TreeServer* ServerSource = FindServer(prefix);
1395                 if (ServerSource)
1396                 {
1397                         ServerSource->SetPingFlag();
1398                 }
1399                 return true;
1400         }
1401         
1402         bool MetaData(std::string prefix, std::deque<std::string> &params)
1403         {
1404                 if (params.size() < 3)
1405                         return true;
1406                 TreeServer* ServerSource = FindServer(prefix);
1407                 if (ServerSource)
1408                 {
1409                         if (*(params[0].c_str()) == '#')
1410                         {
1411                                 chanrec* c = Srv->FindChannel(params[0]);
1412                                 if (c)
1413                                 {
1414                                         FOREACH_MOD OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]);
1415                                 }
1416                         }
1417                         else
1418                         {
1419                                 userrec* u = Srv->FindNick(params[0]);
1420                                 if (u)
1421                                 {
1422                                         FOREACH_MOD OnDecodeMetaData(TYPE_USER,u,params[1],params[2]);
1423                                 }
1424                         }
1425                 }
1426                 params[2] = ":" + params[2];
1427                 DoOneToAllButSender(prefix,"METADATA",params,prefix);
1428                 return true;
1429         }
1430
1431         bool ServerVersion(std::string prefix, std::deque<std::string> &params)
1432         {
1433                 if (params.size() < 1)
1434                         return true;
1435                 TreeServer* ServerSource = FindServer(prefix);
1436                 if (ServerSource)
1437                 {
1438                         ServerSource->SetVersion(params[0]);
1439                 }
1440                 params[0] = ":" + params[0];
1441                 DoOneToAllButSender(prefix,"VERSION",params,prefix);
1442                 return true;
1443         }
1444
1445         bool ChangeHost(std::string prefix, std::deque<std::string> &params)
1446         {
1447                 if (params.size() < 1)
1448                         return true;
1449                 userrec* u = Srv->FindNick(prefix);
1450                 if (u)
1451                 {
1452                         Srv->ChangeHost(u,params[0]);
1453                         DoOneToAllButSender(prefix,"FHOST",params,u->server);
1454                 }
1455                 return true;
1456         }
1457
1458         bool AddLine(std::string prefix, std::deque<std::string> &params)
1459         {
1460                 if (params.size() < 6)
1461                         return true;
1462                 std::string linetype = params[0]; /* Z, Q, E, G, K */
1463                 std::string mask = params[1]; /* Line type dependent */
1464                 std::string source = params[2]; /* may not be online or may be a server */
1465                 std::string settime = params[3]; /* EPOCH time set */
1466                 std::string duration = params[4]; /* Duration secs */
1467                 std::string reason = params[5];
1468
1469                 switch (*(linetype.c_str()))
1470                 {
1471                         case 'Z':
1472                                 add_zline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1473                                 zline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1474                         break;
1475                         case 'Q':
1476                                 add_qline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1477                                 qline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1478                         break;
1479                         case 'E':
1480                                 add_eline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1481                                 eline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1482                         break;
1483                         case 'G':
1484                                 add_gline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1485                                 gline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1486                         break;
1487                         case 'K':
1488                                 add_kline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1489                         break;
1490                         default:
1491                                 /* Just in case... */
1492                                 Srv->SendOpers("*** \2WARNING\2: Invalid xline type '"+linetype+"' sent by server "+prefix+", ignored!");
1493                         break;
1494                 }
1495                 /* Send it on its way */
1496                 params[5] = ":" + params[5];
1497                 DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
1498                 return true;
1499         }
1500
1501         bool ChangeName(std::string prefix, std::deque<std::string> &params)
1502         {
1503                 if (params.size() < 1)
1504                         return true;
1505                 userrec* u = Srv->FindNick(prefix);
1506                 if (u)
1507                 {
1508                         Srv->ChangeGECOS(u,params[0]);
1509                         params[0] = ":" + params[0];
1510                         DoOneToAllButSender(prefix,"FNAME",params,u->server);
1511                 }
1512                 return true;
1513         }
1514
1515         bool Whois(std::string prefix, std::deque<std::string> &params)
1516         {
1517                 if (params.size() < 1)
1518                         return true;
1519                 log(DEBUG,"In IDLE command");
1520                 userrec* u = Srv->FindNick(prefix);
1521                 if (u)
1522                 {
1523                         log(DEBUG,"USER EXISTS: %s",u->nick);
1524                         // an incoming request
1525                         if (params.size() == 1)
1526                         {
1527                                 userrec* x = Srv->FindNick(params[0]);
1528                                 if (x->fd > -1)
1529                                 {
1530                                         userrec* x = Srv->FindNick(params[0]);
1531                                         log(DEBUG,"Got IDLE");
1532                                         char signon[MAXBUF];
1533                                         char idle[MAXBUF];
1534                                         log(DEBUG,"Sending back IDLE 3");
1535                                         snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
1536                                         snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-time(NULL)));
1537                                         std::deque<std::string> par;
1538                                         par.push_back(prefix);
1539                                         par.push_back(signon);
1540                                         par.push_back(idle);
1541                                         // ours, we're done, pass it BACK
1542                                         DoOneToOne(params[0],"IDLE",par,u->server);
1543                                 }
1544                                 else
1545                                 {
1546                                         // not ours pass it on
1547                                         DoOneToOne(prefix,"IDLE",params,x->server);
1548                                 }
1549                         }
1550                         else if (params.size() == 3)
1551                         {
1552                                 std::string who_did_the_whois = params[0];
1553                                 userrec* who_to_send_to = Srv->FindNick(who_did_the_whois);
1554                                 if (who_to_send_to->fd > -1)
1555                                 {
1556                                         log(DEBUG,"Got final IDLE");
1557                                         // an incoming reply to a whois we sent out
1558                                         std::string nick_whoised = prefix;
1559                                         unsigned long signon = atoi(params[1].c_str());
1560                                         unsigned long idle = atoi(params[2].c_str());
1561                                         if ((who_to_send_to) && (who_to_send_to->fd > -1))
1562                                                 do_whois(who_to_send_to,u,signon,idle,(char*)nick_whoised.c_str());
1563                                 }
1564                                 else
1565                                 {
1566                                         // not ours, pass it on
1567                                         DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
1568                                 }
1569                         }
1570                 }
1571                 return true;
1572         }
1573         
1574         bool LocalPing(std::string prefix, std::deque<std::string> &params)
1575         {
1576                 if (params.size() < 1)
1577                         return true;
1578                 std::string stufftobounce = params[0];
1579                 this->WriteLine(":"+Srv->GetServerName()+" PONG "+stufftobounce);
1580                 return true;
1581         }
1582
1583         bool RemoteServer(std::string prefix, std::deque<std::string> &params)
1584         {
1585                 if (params.size() < 4)
1586                         return false;
1587                 std::string servername = params[0];
1588                 std::string password = params[1];
1589                 // hopcount is not used for a remote server, we calculate this ourselves
1590                 std::string description = params[3];
1591                 TreeServer* ParentOfThis = FindServer(prefix);
1592                 if (!ParentOfThis)
1593                 {
1594                         this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
1595                         return false;
1596                 }
1597                 TreeServer* CheckDupe = FindServer(servername);
1598                 if (CheckDupe)
1599                 {
1600                         this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1601                         Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1602                         return false;
1603                 }
1604                 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
1605                 ParentOfThis->AddChild(Node);
1606                 params[3] = ":" + params[3];
1607                 DoOneToAllButSender(prefix,"SERVER",params,prefix);
1608                 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
1609                 return true;
1610         }
1611
1612         bool Outbound_Reply_Server(std::deque<std::string> &params)
1613         {
1614                 if (params.size() < 4)
1615                         return false;
1616                 std::string servername = params[0];
1617                 std::string password = params[1];
1618                 int hops = atoi(params[2].c_str());
1619                 if (hops)
1620                 {
1621                         this->WriteLine("ERROR :Server too far away for authentication");
1622                         Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, server is too far away for authentication");
1623                         return false;
1624                 }
1625                 std::string description = params[3];
1626                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1627                 {
1628                         if ((x->Name == servername) && (x->RecvPass == password))
1629                         {
1630                                 TreeServer* CheckDupe = FindServer(servername);
1631                                 if (CheckDupe)
1632                                 {
1633                                         this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1634                                         Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1635                                         return false;
1636                                 }
1637                                 // Begin the sync here. this kickstarts the
1638                                 // other side, waiting in WAIT_AUTH_2 state,
1639                                 // into starting their burst, as it shows
1640                                 // that we're happy.
1641                                 this->LinkState = CONNECTED;
1642                                 // we should add the details of this server now
1643                                 // to the servers tree, as a child of the root
1644                                 // node.
1645                                 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
1646                                 TreeRoot->AddChild(Node);
1647                                 params[3] = ":" + params[3];
1648                                 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
1649                                 this->bursting = true;
1650                                 this->DoBurst(Node);
1651                                 return true;
1652                         }
1653                 }
1654                 this->WriteLine("ERROR :Invalid credentials");
1655                 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, invalid link credentials");
1656                 return false;
1657         }
1658
1659         bool Inbound_Server(std::deque<std::string> &params)
1660         {
1661                 if (params.size() < 4)
1662                         return false;
1663                 std::string servername = params[0];
1664                 std::string password = params[1];
1665                 int hops = atoi(params[2].c_str());
1666                 if (hops)
1667                 {
1668                         this->WriteLine("ERROR :Server too far away for authentication");
1669                         Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, server is too far away for authentication");
1670                         return false;
1671                 }
1672                 std::string description = params[3];
1673                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1674                 {
1675                         if ((x->Name == servername) && (x->RecvPass == password))
1676                         {
1677                                 TreeServer* CheckDupe = FindServer(servername);
1678                                 if (CheckDupe)
1679                                 {
1680                                         this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1681                                         Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1682                                         return false;
1683                                 }
1684                                 /* If the config says this link is encrypted, but the remote side
1685                                  * hasnt bothered to send the AES command before SERVER, then we
1686                                  * boot them off as we MUST have this connection encrypted.
1687                                  */
1688                                 if ((x->EncryptionKey != "") && (!this->ctx))
1689                                 {
1690                                         this->WriteLine("ERROR :This link requires AES encryption to be enabled. Plaintext connection refused.");
1691                                         Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, remote server did not enable AES.");
1692                                         return false;
1693                                 }
1694                                 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
1695                                 this->InboundServerName = servername;
1696                                 this->InboundDescription = description;
1697                                 // this is good. Send our details: Our server name and description and hopcount of 0,
1698                                 // along with the sendpass from this block.
1699                                 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
1700                                 // move to the next state, we are now waiting for THEM.
1701                                 this->LinkState = WAIT_AUTH_2;
1702                                 return true;
1703                         }
1704                 }
1705                 this->WriteLine("ERROR :Invalid credentials");
1706                 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, invalid link credentials");
1707                 return false;
1708         }
1709
1710         void Split(std::string line, bool stripcolon, std::deque<std::string> &n)
1711         {
1712                 if (!strchr(line.c_str(),' '))
1713                 {
1714                         n.push_back(line);
1715                         return;
1716                 }
1717                 std::stringstream s(line);
1718                 std::string param = "";
1719                 n.clear();
1720                 int item = 0;
1721                 while (!s.eof())
1722                 {
1723                         char c;
1724                         s.get(c);
1725                         if (c == ' ')
1726                         {
1727                                 n.push_back(param);
1728                                 param = "";
1729                                 item++;
1730                         }
1731                         else
1732                         {
1733                                 if (!s.eof())
1734                                 {
1735                                         param = param + c;
1736                                 }
1737                                 if ((param == ":") && (item > 0))
1738                                 {
1739                                         param = "";
1740                                         while (!s.eof())
1741                                         {
1742                                                 s.get(c);
1743                                                 if (!s.eof())
1744                                                 {
1745                                                         param = param + c;
1746                                                 }
1747                                         }
1748                                         n.push_back(param);
1749                                         param = "";
1750                                 }
1751                         }
1752                 }
1753                 if (param != "")
1754                 {
1755                         n.push_back(param);
1756                 }
1757                 return;
1758         }
1759
1760         bool ProcessLine(std::string line)
1761         {
1762                 char* l = (char*)line.c_str();
1763                 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
1764                         l[strlen(l)-1] = '\0';
1765                 line = l;
1766                 if (line == "")
1767                         return true;
1768                 Srv->Log(DEBUG,"IN: "+line);
1769                 std::deque<std::string> params;
1770                 this->Split(line,true,params);
1771                 std::string command = "";
1772                 std::string prefix = "";
1773                 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
1774                 {
1775                         prefix = params[0];
1776                         command = params[1];
1777                         char* pref = (char*)prefix.c_str();
1778                         prefix = ++pref;
1779                         params.pop_front();
1780                         params.pop_front();
1781                 }
1782                 else
1783                 {
1784                         prefix = "";
1785                         command = params[0];
1786                         params.pop_front();
1787                 }
1788
1789                 if ((!this->ctx) && (command == "AES"))
1790                 {
1791                         std::string sserv = params[0];
1792                         for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1793                         {
1794                                 if ((x->EncryptionKey != "") && (x->Name == sserv))
1795                                 {
1796                                         this->InitAES(x->EncryptionKey,sserv);
1797                                 }
1798                         }
1799                         return true;
1800                 }
1801                 else if ((this->ctx) && (command == "AES"))
1802                 {
1803                         WriteOpers("*** \2AES\2: Encryption already enabled on this connection yet %s is trying to enable it twice!",params[0].c_str());
1804                 }
1805
1806                 switch (this->LinkState)
1807                 {
1808                         TreeServer* Node;
1809                         
1810                         case WAIT_AUTH_1:
1811                                 // Waiting for SERVER command from remote server. Server initiating
1812                                 // the connection sends the first SERVER command, listening server
1813                                 // replies with theirs if its happy, then if the initiator is happy,
1814                                 // it starts to send its net sync, which starts the merge, otherwise
1815                                 // it sends an ERROR.
1816                                 if (command == "PASS")
1817                                 {
1818                                         /* Silently ignored */
1819                                 }
1820                                 else if (command == "SERVER")
1821                                 {
1822                                         return this->Inbound_Server(params);
1823                                 }
1824                                 else if (command == "ERROR")
1825                                 {
1826                                         return this->Error(params);
1827                                 }
1828                                 else if (command == "USER")
1829                                 {
1830                                         this->WriteLine("ERROR :Client connections to this port are prohibited.");
1831                                         return false;
1832                                 }
1833                                 else if (command == "CAPAB")
1834                                 {
1835                                         return this->Capab(params);
1836                                 }
1837                                 else
1838                                 {
1839                                         this->WriteLine("ERROR :Invalid command in negotiation phase.");
1840                                         return false;
1841                                 }
1842                         break;
1843                         case WAIT_AUTH_2:
1844                                 // Waiting for start of other side's netmerge to say they liked our
1845                                 // password.
1846                                 if (command == "SERVER")
1847                                 {
1848                                         // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1849                                         // silently ignore.
1850                                         return true;
1851                                 }
1852                                 else if (command == "BURST")
1853                                 {
1854                                         this->LinkState = CONNECTED;
1855                                         Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
1856                                         TreeRoot->AddChild(Node);
1857                                         params.clear();
1858                                         params.push_back(InboundServerName);
1859                                         params.push_back("*");
1860                                         params.push_back("1");
1861                                         params.push_back(":"+InboundDescription);
1862                                         DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
1863                                         this->bursting = true;
1864                                         this->DoBurst(Node);
1865                                 }
1866                                 else if (command == "ERROR")
1867                                 {
1868                                         return this->Error(params);
1869                                 }
1870                                 else if (command == "CAPAB")
1871                                 {
1872                                         return this->Capab(params);
1873                                 }
1874                                 
1875                         break;
1876                         case LISTENER:
1877                                 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
1878                                 return false;
1879                         break;
1880                         case CONNECTING:
1881                                 if (command == "SERVER")
1882                                 {
1883                                         // another server we connected to, which was in WAIT_AUTH_1 state,
1884                                         // has just sent us their credentials. If we get this far, theyre
1885                                         // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1886                                         // if we're happy with this, we should send our netburst which
1887                                         // kickstarts the merge.
1888                                         return this->Outbound_Reply_Server(params);
1889                                 }
1890                                 else if (command == "ERROR")
1891                                 {
1892                                         return this->Error(params);
1893                                 }
1894                         break;
1895                         case CONNECTED:
1896                                 // This is the 'authenticated' state, when all passwords
1897                                 // have been exchanged and anything past this point is taken
1898                                 // as gospel.
1899                                 
1900                                 if (prefix != "")
1901                                 {
1902                                         std::string direction = prefix;
1903                                         userrec* t = Srv->FindNick(prefix);
1904                                         if (t)
1905                                         {
1906                                                 direction = t->server;
1907                                         }
1908                                         TreeServer* route_back_again = BestRouteTo(direction);
1909                                         if ((!route_back_again) || (route_back_again->GetSocket() != this))
1910                                         {
1911                                                 if (route_back_again)
1912                                                 {
1913                                                         WriteOpers("*** Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
1914                                                 }
1915                                                 else
1916                                                 {
1917                                                         WriteOpers("*** Protocol violation: Invalid source '%s' in command '%s' from connection '%s'",direction.c_str(),line.c_str(),this->GetName().c_str());
1918                                                 }
1919                                                 
1920                                                 return true;
1921                                         }
1922                                 }
1923                                 
1924                                 if (command == "SVSMODE")
1925                                 {
1926                                         /* Services expects us to implement
1927                                          * SVSMODE. In inspircd its the same as
1928                                          * MODE anyway.
1929                                          */
1930                                         command = "MODE";
1931                                 }
1932                                 std::string target = "";
1933                                 /* Yes, know, this is a mess. Its reasonably fast though as we're
1934                                  * working with std::string here.
1935                                  */
1936                                 if ((command == "NICK") && (params.size() > 1))
1937                                 {
1938                                         return this->IntroduceClient(prefix,params);
1939                                 }
1940                                 else if (command == "FJOIN")
1941                                 {
1942                                         return this->ForceJoin(prefix,params);
1943                                 }
1944                                 else if (command == "SERVER")
1945                                 {
1946                                         return this->RemoteServer(prefix,params);
1947                                 }
1948                                 else if (command == "ERROR")
1949                                 {
1950                                         return this->Error(params);
1951                                 }
1952                                 else if (command == "OPERTYPE")
1953                                 {
1954                                         return this->OperType(prefix,params);
1955                                 }
1956                                 else if (command == "FMODE")
1957                                 {
1958                                         return this->ForceMode(prefix,params);
1959                                 }
1960                                 else if (command == "KILL")
1961                                 {
1962                                         return this->RemoteKill(prefix,params);
1963                                 }
1964                                 else if (command == "FTOPIC")
1965                                 {
1966                                         return this->ForceTopic(prefix,params);
1967                                 }
1968                                 else if (command == "REHASH")
1969                                 {
1970                                         return this->RemoteRehash(prefix,params);
1971                                 }
1972                                 else if (command == "METADATA")
1973                                 {
1974                                         return this->MetaData(prefix,params);
1975                                 }
1976                                 else if (command == "PING")
1977                                 {
1978                                         return this->LocalPing(prefix,params);
1979                                 }
1980                                 else if (command == "PONG")
1981                                 {
1982                                         return this->LocalPong(prefix,params);
1983                                 }
1984                                 else if (command == "VERSION")
1985                                 {
1986                                         return this->ServerVersion(prefix,params);
1987                                 }
1988                                 else if (command == "FHOST")
1989                                 {
1990                                         return this->ChangeHost(prefix,params);
1991                                 }
1992                                 else if (command == "FNAME")
1993                                 {
1994                                         return this->ChangeName(prefix,params);
1995                                 }
1996                                 else if (command == "ADDLINE")
1997                                 {
1998                                         return this->AddLine(prefix,params);
1999                                 }
2000                                 else if (command == "SVSNICK")
2001                                 {
2002                                         if (prefix == "")
2003                                         {
2004                                                 prefix = this->GetName();
2005                                         }
2006                                         return this->ForceNick(prefix,params);
2007                                 }
2008                                 else if (command == "IDLE")
2009                                 {
2010                                         return this->Whois(prefix,params);
2011                                 }
2012                                 else if (command == "SVSJOIN")
2013                                 {
2014                                         if (prefix == "")
2015                                         {
2016                                                 prefix = this->GetName();
2017                                         }
2018                                         return this->ServiceJoin(prefix,params);
2019                                 }
2020                                 else if (command == "SQUIT")
2021                                 {
2022                                         if (params.size() == 2)
2023                                         {
2024                                                 this->Squit(FindServer(params[0]),params[1]);
2025                                         }
2026                                         return true;
2027                                 }
2028                                 else if (command == "ENDBURST")
2029                                 {
2030                                         this->bursting = false;
2031                                         return true;
2032                                 }
2033                                 else
2034                                 {
2035                                         // not a special inter-server command.
2036                                         // Emulate the actual user doing the command,
2037                                         // this saves us having a huge ugly parser.
2038                                         userrec* who = Srv->FindNick(prefix);
2039                                         std::string sourceserv = this->myhost;
2040                                         if (this->InboundServerName != "")
2041                                         {
2042                                                 sourceserv = this->InboundServerName;
2043                                         }
2044                                         if (who)
2045                                         {
2046                                                 // its a user
2047                                                 target = who->server;
2048                                                 char* strparams[127];
2049                                                 for (unsigned int q = 0; q < params.size(); q++)
2050                                                 {
2051                                                         strparams[q] = (char*)params[q].c_str();
2052                                                 }
2053                                                 Srv->CallCommandHandler(command, strparams, params.size(), who);
2054                                         }
2055                                         else
2056                                         {
2057                                                 // its not a user. Its either a server, or somethings screwed up.
2058                                                 if (IsServer(prefix))
2059                                                 {
2060                                                         target = Srv->GetServerName();
2061                                                 }
2062                                                 else
2063                                                 {
2064                                                         log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
2065                                                         return true;
2066                                                 }
2067                                         }
2068                                         return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
2069
2070                                 }
2071                                 return true;
2072                         break;
2073                 }
2074                 return true;
2075         }
2076
2077         virtual std::string GetName()
2078         {
2079                 std::string sourceserv = this->myhost;
2080                 if (this->InboundServerName != "")
2081                 {
2082                         sourceserv = this->InboundServerName;
2083                 }
2084                 return sourceserv;
2085         }
2086
2087         virtual void OnTimeout()
2088         {
2089                 if (this->LinkState == CONNECTING)
2090                 {
2091                         Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
2092                 }
2093         }
2094
2095         virtual void OnClose()
2096         {
2097                 // Connection closed.
2098                 // If the connection is fully up (state CONNECTED)
2099                 // then propogate a netsplit to all peers.
2100                 std::string quitserver = this->myhost;
2101                 if (this->InboundServerName != "")
2102                 {
2103                         quitserver = this->InboundServerName;
2104                 }
2105                 TreeServer* s = FindServer(quitserver);
2106                 if (s)
2107                 {
2108                         Squit(s,"Remote host closed the connection");
2109                 }
2110                 WriteOpers("Server '\2%s\2[%s]' closed the connection.",quitserver.c_str(),this->GetIP().c_str());
2111         }
2112
2113         virtual int OnIncomingConnection(int newsock, char* ip)
2114         {
2115                 TreeSocket* s = new TreeSocket(newsock, ip);
2116                 Srv->AddSocket(s);
2117                 return true;
2118         }
2119 };
2120
2121 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
2122 {
2123         for (unsigned int c = 0; c < list.size(); c++)
2124         {
2125                 if (list[c] == server)
2126                 {
2127                         return;
2128                 }
2129         }
2130         list.push_back(server);
2131 }
2132
2133 // returns a list of DIRECT servernames for a specific channel
2134 void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
2135 {
2136         std::vector<char*> *ulist = c->GetUsers();
2137         unsigned int ucount = ulist->size();
2138         for (unsigned int i = 0; i < ucount; i++)
2139         {
2140                 char* o = (*ulist)[i];
2141                 userrec* otheruser = (userrec*)o;
2142                 if (otheruser->fd < 0)
2143                 {
2144                         TreeServer* best = BestRouteTo(otheruser->server);
2145                         if (best)
2146                                 AddThisServer(best,list);
2147                 }
2148         }
2149         return;
2150 }
2151
2152 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, std::string command, std::deque<std::string> &params)
2153 {
2154         TreeServer* omitroute = BestRouteTo(omit);
2155         if ((command == "NOTICE") || (command == "PRIVMSG"))
2156         {
2157                 if ((params.size() >= 2) && (*(params[0].c_str()) != '$'))
2158                 {
2159                         if (*(params[0].c_str()) != '#')
2160                         {
2161                                 // special routing for private messages/notices
2162                                 userrec* d = Srv->FindNick(params[0]);
2163                                 if (d)
2164                                 {
2165                                         std::deque<std::string> par;
2166                                         par.push_back(params[0]);
2167                                         par.push_back(":"+params[1]);
2168                                         DoOneToOne(prefix,command,par,d->server);
2169                                         return true;
2170                                 }
2171                         }
2172                         else
2173                         {
2174                                 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
2175                                 chanrec* c = Srv->FindChannel(params[0]);
2176                                 if (c)
2177                                 {
2178                                         std::deque<TreeServer*> list;
2179                                         GetListOfServersForChannel(c,list);
2180                                         log(DEBUG,"Got a list of %d servers",list.size());
2181                                         unsigned int lsize = list.size();
2182                                         for (unsigned int i = 0; i < lsize; i++)
2183                                         {
2184                                                 TreeSocket* Sock = list[i]->GetSocket();
2185                                                 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
2186                                                 {
2187                                                         log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
2188                                                         Sock->WriteLine(data);
2189                                                 }
2190                                         }
2191                                         return true;
2192                                 }
2193                         }
2194                 }
2195         }
2196         unsigned int items = TreeRoot->ChildCount();
2197         for (unsigned int x = 0; x < items; x++)
2198         {
2199                 TreeServer* Route = TreeRoot->GetChild(x);
2200                 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
2201                 {
2202                         TreeSocket* Sock = Route->GetSocket();
2203                         Sock->WriteLine(data);
2204                 }
2205         }
2206         return true;
2207 }
2208
2209 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> &params, std::string omit)
2210 {
2211         TreeServer* omitroute = BestRouteTo(omit);
2212         std::string FullLine = ":" + prefix + " " + command;
2213         unsigned int words = params.size();
2214         for (unsigned int x = 0; x < words; x++)
2215         {
2216                 FullLine = FullLine + " " + params[x];
2217         }
2218         unsigned int items = TreeRoot->ChildCount();
2219         for (unsigned int x = 0; x < items; x++)
2220         {
2221                 TreeServer* Route = TreeRoot->GetChild(x);
2222                 // Send the line IF:
2223                 // The route has a socket (its a direct connection)
2224                 // The route isnt the one to be omitted
2225                 // The route isnt the path to the one to be omitted
2226                 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
2227                 {
2228                         TreeSocket* Sock = Route->GetSocket();
2229                         Sock->WriteLine(FullLine);
2230                 }
2231         }
2232         return true;
2233 }
2234
2235 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> &params)
2236 {
2237         std::string FullLine = ":" + prefix + " " + command;
2238         unsigned int words = params.size();
2239         for (unsigned int x = 0; x < words; x++)
2240         {
2241                 FullLine = FullLine + " " + params[x];
2242         }
2243         unsigned int items = TreeRoot->ChildCount();
2244         for (unsigned int x = 0; x < items; x++)
2245         {
2246                 TreeServer* Route = TreeRoot->GetChild(x);
2247                 if (Route->GetSocket())
2248                 {
2249                         TreeSocket* Sock = Route->GetSocket();
2250                         Sock->WriteLine(FullLine);
2251                 }
2252         }
2253         return true;
2254 }
2255
2256 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> &params, std::string target)
2257 {
2258         TreeServer* Route = BestRouteTo(target);
2259         if (Route)
2260         {
2261                 std::string FullLine = ":" + prefix + " " + command;
2262                 unsigned int words = params.size();
2263                 for (unsigned int x = 0; x < words; x++)
2264                 {
2265                         FullLine = FullLine + " " + params[x];
2266                 }
2267                 if (Route->GetSocket())
2268                 {
2269                         TreeSocket* Sock = Route->GetSocket();
2270                         Sock->WriteLine(FullLine);
2271                 }
2272                 return true;
2273         }
2274         else
2275         {
2276                 return true;
2277         }
2278 }
2279
2280 std::vector<TreeSocket*> Bindings;
2281
2282 void ReadConfiguration(bool rebind)
2283 {
2284         Conf = new ConfigReader;
2285         if (rebind)
2286         {
2287                 for (int j =0; j < Conf->Enumerate("bind"); j++)
2288                 {
2289                         std::string Type = Conf->ReadValue("bind","type",j);
2290                         std::string IP = Conf->ReadValue("bind","address",j);
2291                         long Port = Conf->ReadInteger("bind","port",j,true);
2292                         if (Type == "servers")
2293                         {
2294                                 if (IP == "*")
2295                                 {
2296                                         IP = "";
2297                                 }
2298                                 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
2299                                 if (listener->GetState() == I_LISTENING)
2300                                 {
2301                                         Srv->AddSocket(listener);
2302                                         Bindings.push_back(listener);
2303                                 }
2304                                 else
2305                                 {
2306                                         log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
2307                                         listener->Close();
2308                                         delete listener;
2309                                 }
2310                         }
2311                 }
2312         }
2313         LinkBlocks.clear();
2314         for (int j =0; j < Conf->Enumerate("link"); j++)
2315         {
2316                 Link L;
2317                 L.Name = Conf->ReadValue("link","name",j);
2318                 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
2319                 L.Port = Conf->ReadInteger("link","port",j,true);
2320                 L.SendPass = Conf->ReadValue("link","sendpass",j);
2321                 L.RecvPass = Conf->ReadValue("link","recvpass",j);
2322                 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
2323                 L.EncryptionKey =  Conf->ReadValue("link","encryptionkey",j);
2324                 L.NextConnectTime = time(NULL) + L.AutoConnect;
2325                 /* Bugfix by brain, do not allow people to enter bad configurations */
2326                 if ((L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
2327                 {
2328                         LinkBlocks.push_back(L);
2329                         log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
2330                 }
2331                 else
2332                 {
2333                         log(DEFAULT,"m_spanningtree: Invalid configuration for server '%s', ignored!",L.Name.c_str());
2334                 }
2335         }
2336         delete Conf;
2337 }
2338
2339
2340 class ModuleSpanningTree : public Module
2341 {
2342         std::vector<TreeSocket*> Bindings;
2343         int line;
2344         int NumServers;
2345
2346  public:
2347
2348         ModuleSpanningTree(Server* Me)
2349                 : Module::Module(Me)
2350         {
2351                 Srv = Me;
2352                 Bindings.clear();
2353
2354                 // Create the root of the tree
2355                 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
2356
2357                 ReadConfiguration(true);
2358         }
2359
2360         void ShowLinks(TreeServer* Current, userrec* user, int hops)
2361         {
2362                 std::string Parent = TreeRoot->GetName();
2363                 if (Current->GetParent())
2364                 {
2365                         Parent = Current->GetParent()->GetName();
2366                 }
2367                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
2368                 {
2369                         ShowLinks(Current->GetChild(q),user,hops+1);
2370                 }
2371                 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
2372         }
2373
2374         int CountLocalServs()
2375         {
2376                 return TreeRoot->ChildCount();
2377         }
2378
2379         int CountServs()
2380         {
2381                 return serverlist.size();
2382         }
2383
2384         void HandleLinks(char** parameters, int pcnt, userrec* user)
2385         {
2386                 ShowLinks(TreeRoot,user,0);
2387                 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
2388                 return;
2389         }
2390
2391         void HandleLusers(char** parameters, int pcnt, userrec* user)
2392         {
2393                 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),this->CountServs());
2394                 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
2395                 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
2396                 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
2397                 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
2398                 return;
2399         }
2400
2401         // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
2402
2403         void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
2404         {
2405                 if (line < 128)
2406                 {
2407                         for (int t = 0; t < depth; t++)
2408                         {
2409                                 matrix[line][t] = ' ';
2410                         }
2411                         strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
2412                         line++;
2413                         for (unsigned int q = 0; q < Current->ChildCount(); q++)
2414                         {
2415                                 ShowMap(Current->GetChild(q),user,depth+2,matrix);
2416                         }
2417                 }
2418         }
2419
2420         // Ok, prepare to be confused.
2421         // After much mulling over how to approach this, it struck me that
2422         // the 'usual' way of doing a /MAP isnt the best way. Instead of
2423         // keeping track of a ton of ascii characters, and line by line
2424         // under recursion working out where to place them using multiplications
2425         // and divisons, we instead render the map onto a backplane of characters
2426         // (a character matrix), then draw the branches as a series of "L" shapes
2427         // from the nodes. This is not only friendlier on CPU it uses less stack.
2428
2429         void HandleMap(char** parameters, int pcnt, userrec* user)
2430         {
2431                 // This array represents a virtual screen which we will
2432                 // "scratch" draw to, as the console device of an irc
2433                 // client does not provide for a proper terminal.
2434                 char matrix[128][80];
2435                 for (unsigned int t = 0; t < 128; t++)
2436                 {
2437                         matrix[t][0] = '\0';
2438                 }
2439                 line = 0;
2440                 // The only recursive bit is called here.
2441                 ShowMap(TreeRoot,user,0,matrix);
2442                 // Process each line one by one. The algorithm has a limit of
2443                 // 128 servers (which is far more than a spanning tree should have
2444                 // anyway, so we're ok). This limit can be raised simply by making
2445                 // the character matrix deeper, 128 rows taking 10k of memory.
2446                 for (int l = 1; l < line; l++)
2447                 {
2448                         // scan across the line looking for the start of the
2449                         // servername (the recursive part of the algorithm has placed
2450                         // the servers at indented positions depending on what they
2451                         // are related to)
2452                         int first_nonspace = 0;
2453                         while (matrix[l][first_nonspace] == ' ')
2454                         {
2455                                 first_nonspace++;
2456                         }
2457                         first_nonspace--;
2458                         // Draw the `- (corner) section: this may be overwritten by
2459                         // another L shape passing along the same vertical pane, becoming
2460                         // a |- (branch) section instead.
2461                         matrix[l][first_nonspace] = '-';
2462                         matrix[l][first_nonspace-1] = '`';
2463                         int l2 = l - 1;
2464                         // Draw upwards until we hit the parent server, causing possibly
2465                         // other corners (`-) to become branches (|-)
2466                         while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
2467                         {
2468                                 matrix[l2][first_nonspace-1] = '|';
2469                                 l2--;
2470                         }
2471                 }
2472                 // dump the whole lot to the user. This is the easy bit, honest.
2473                 for (int t = 0; t < line; t++)
2474                 {
2475                         WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
2476                 }
2477                 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
2478                 return;
2479         }
2480
2481         int HandleSquit(char** parameters, int pcnt, userrec* user)
2482         {
2483                 TreeServer* s = FindServerMask(parameters[0]);
2484                 if (s)
2485                 {
2486                         if (s == TreeRoot)
2487                         {
2488                                  WriteServ(user->fd,"NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
2489                                 return 1;
2490                         }
2491                         TreeSocket* sock = s->GetSocket();
2492                         if (sock)
2493                         {
2494                                 log(DEBUG,"Splitting server %s",s->GetName().c_str());
2495                                 WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
2496                                 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
2497                                 sock->Close();
2498                         }
2499                         else
2500                         {
2501                                 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
2502                         }
2503                 }
2504                 else
2505                 {
2506                          WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
2507                 }
2508                 return 1;
2509         }
2510
2511         int HandleRemoteWhois(char** parameters, int pcnt, userrec* user)
2512         {
2513                 if ((user->fd > -1) && (pcnt > 1))
2514                 {
2515                         userrec* remote = Srv->FindNick(parameters[1]);
2516                         if ((remote) && (remote->fd < 0))
2517                         {
2518                                 std::deque<std::string> params;
2519                                 params.push_back(parameters[1]);
2520                                 DoOneToOne(user->nick,"IDLE",params,remote->server);
2521                                 return 1;
2522                         }
2523                         else if (!remote)
2524                         {
2525                                 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
2526                                 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
2527                                 return 1;
2528                         }
2529                 }
2530                 return 0;
2531         }
2532
2533         void DoPingChecks(time_t curtime)
2534         {
2535                 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
2536                 {
2537                         TreeServer* serv = TreeRoot->GetChild(j);
2538                         TreeSocket* sock = serv->GetSocket();
2539                         if (sock)
2540                         {
2541                                 if (curtime >= serv->NextPingTime())
2542                                 {
2543                                         if (serv->AnsweredLastPing())
2544                                         {
2545                                                 sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
2546                                                 serv->SetNextPingTime(curtime + 60);
2547                                         }
2548                                         else
2549                                         {
2550                                                 // they didnt answer, boot them
2551                                                 WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
2552                                                 sock->Squit(serv,"Ping timeout");
2553                                                 sock->Close();
2554                                                 return;
2555                                         }
2556                                 }
2557                         }
2558                 }
2559         }
2560
2561         void AutoConnectServers(time_t curtime)
2562         {
2563                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2564                 {
2565                         if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
2566                         {
2567                                 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
2568                                 x->NextConnectTime = curtime + x->AutoConnect;
2569                                 TreeServer* CheckDupe = FindServer(x->Name);
2570                                 if (!CheckDupe)
2571                                 {
2572                                         // an autoconnected server is not connected. Check if its time to connect it
2573                                         WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
2574                                         TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2575                                         Srv->AddSocket(newsocket);
2576                                 }
2577                         }
2578                 }
2579         }
2580
2581         int HandleVersion(char** parameters, int pcnt, userrec* user)
2582         {
2583                 // we've already checked if pcnt > 0, so this is safe
2584                 TreeServer* found = FindServerMask(parameters[0]);
2585                 if (found)
2586                 {
2587                         std::string Version = found->GetVersion();
2588                         WriteServ(user->fd,"351 %s :%s",user->nick,Version.c_str());
2589                 }
2590                 else
2591                 {
2592                         WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
2593                 }
2594                 return 1;
2595         }
2596         
2597         int HandleConnect(char** parameters, int pcnt, userrec* user)
2598         {
2599                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2600                 {
2601                         if (Srv->MatchText(x->Name.c_str(),parameters[0]))
2602                         {
2603                                 TreeServer* CheckDupe = FindServer(x->Name);
2604                                 if (!CheckDupe)
2605                                 {
2606                                         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);
2607                                         TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2608                                         Srv->AddSocket(newsocket);
2609                                         return 1;
2610                                 }
2611                                 else
2612                                 {
2613                                         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());
2614                                         return 1;
2615                                 }
2616                         }
2617                 }
2618                 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
2619                 return 1;
2620         }
2621
2622         virtual bool HandleStats(char ** parameters, int pcnt, userrec* user)
2623         {
2624                 if (*parameters[0] == 'c')
2625                 {
2626                         for (unsigned int i = 0; i < LinkBlocks.size(); i++)
2627                         {
2628                                 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"));
2629                                 WriteServ(user->fd,"244 %s H * * %s",user->nick,LinkBlocks[i].Name.c_str());
2630                         }
2631                         WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
2632                         WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
2633                         return true;
2634                 }
2635                 return false;
2636         }
2637
2638         virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
2639         {
2640                 if (command == "CONNECT")
2641                 {
2642                         return this->HandleConnect(parameters,pcnt,user);
2643                 }
2644                 else if (command == "SQUIT")
2645                 {
2646                         return this->HandleSquit(parameters,pcnt,user);
2647                 }
2648                 else if (command == "STATS")
2649                 {
2650                         return this->HandleStats(parameters,pcnt,user);
2651                 }
2652                 else if (command == "MAP")
2653                 {
2654                         this->HandleMap(parameters,pcnt,user);
2655                         return 1;
2656                 }
2657                 else if (command == "LUSERS")
2658                 {
2659                         this->HandleLusers(parameters,pcnt,user);
2660                         return 1;
2661                 }
2662                 else if (command == "LINKS")
2663                 {
2664                         this->HandleLinks(parameters,pcnt,user);
2665                         return 1;
2666                 }
2667                 else if (command == "WHOIS")
2668                 {
2669                         if (pcnt > 1)
2670                         {
2671                                 // remote whois
2672                                 return this->HandleRemoteWhois(parameters,pcnt,user);
2673                         }
2674                 }
2675                 else if ((command == "VERSION") && (pcnt > 0))
2676                 {
2677                         this->HandleVersion(parameters,pcnt,user);
2678                         return 1;
2679                 }
2680                 else if (Srv->IsValidModuleCommand(command, pcnt, user))
2681                 {
2682                         // this bit of code cleverly routes all module commands
2683                         // to all remote severs *automatically* so that modules
2684                         // can just handle commands locally, without having
2685                         // to have any special provision in place for remote
2686                         // commands and linking protocols.
2687                         std::deque<std::string> params;
2688                         params.clear();
2689                         for (int j = 0; j < pcnt; j++)
2690                         {
2691                                 if (strchr(parameters[j],' '))
2692                                 {
2693                                         params.push_back(":" + std::string(parameters[j]));
2694                                 }
2695                                 else
2696                                 {
2697                                         params.push_back(std::string(parameters[j]));
2698                                 }
2699                         }
2700                         DoOneToMany(user->nick,command,params);
2701                 }
2702                 return 0;
2703         }
2704
2705         virtual void OnGetServerDescription(std::string servername,std::string &description)
2706         {
2707                 TreeServer* s = FindServer(servername);
2708                 if (s)
2709                 {
2710                         description = s->GetDesc();
2711                 }
2712         }
2713
2714         virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
2715         {
2716                 if (source->fd > -1)
2717                 {
2718                         std::deque<std::string> params;
2719                         params.push_back(dest->nick);
2720                         params.push_back(channel->name);
2721                         DoOneToMany(source->nick,"INVITE",params);
2722                 }
2723         }
2724
2725         virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
2726         {
2727                 std::deque<std::string> params;
2728                 params.push_back(chan->name);
2729                 params.push_back(":"+topic);
2730                 DoOneToMany(user->nick,"TOPIC",params);
2731         }
2732
2733         virtual void OnWallops(userrec* user, std::string text)
2734         {
2735                 if (user->fd > -1)
2736                 {
2737                         std::deque<std::string> params;
2738                         params.push_back(":"+text);
2739                         DoOneToMany(user->nick,"WALLOPS",params);
2740                 }
2741         }
2742
2743         virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
2744         {
2745                 if (target_type == TYPE_USER)
2746                 {
2747                         userrec* d = (userrec*)dest;
2748                         if ((d->fd < 0) && (user->fd > -1))
2749                         {
2750                                 std::deque<std::string> params;
2751                                 params.clear();
2752                                 params.push_back(d->nick);
2753                                 params.push_back(":"+text);
2754                                 DoOneToOne(user->nick,"NOTICE",params,d->server);
2755                         }
2756                 }
2757                 else
2758                 {
2759                         if (user->fd > -1)
2760                         {
2761                                 chanrec *c = (chanrec*)dest;
2762                                 std::deque<TreeServer*> list;
2763                                 GetListOfServersForChannel(c,list);
2764                                 unsigned int ucount = list.size();
2765                                 for (unsigned int i = 0; i < ucount; i++)
2766                                 {
2767                                         TreeSocket* Sock = list[i]->GetSocket();
2768                                         if (Sock)
2769                                                 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+std::string(c->name)+" :"+text);
2770                                 }
2771                         }
2772                 }
2773         }
2774
2775         virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
2776         {
2777                 if (target_type == TYPE_USER)
2778                 {
2779                         // route private messages which are targetted at clients only to the server
2780                         // which needs to receive them
2781                         userrec* d = (userrec*)dest;
2782                         if ((d->fd < 0) && (user->fd > -1))
2783                         {
2784                                 std::deque<std::string> params;
2785                                 params.clear();
2786                                 params.push_back(d->nick);
2787                                 params.push_back(":"+text);
2788                                 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
2789                         }
2790                 }
2791                 else
2792                 {
2793                         if (user->fd > -1)
2794                         {
2795                                 chanrec *c = (chanrec*)dest;
2796                                 std::deque<TreeServer*> list;
2797                                 GetListOfServersForChannel(c,list);
2798                                 unsigned int ucount = list.size();
2799                                 for (unsigned int i = 0; i < ucount; i++)
2800                                 {
2801                                         TreeSocket* Sock = list[i]->GetSocket();
2802                                         if (Sock)
2803                                                 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+std::string(c->name)+" :"+text);
2804                                 }
2805                         }
2806                 }
2807         }
2808
2809         virtual void OnBackgroundTimer(time_t curtime)
2810         {
2811                 AutoConnectServers(curtime);
2812                 DoPingChecks(curtime);
2813         }
2814
2815         virtual void OnUserJoin(userrec* user, chanrec* channel)
2816         {
2817                 // Only do this for local users
2818                 if (user->fd > -1)
2819                 {
2820                         std::deque<std::string> params;
2821                         params.clear();
2822                         params.push_back(channel->name);
2823                         if (*channel->key)
2824                         {
2825                                 // if the channel has a key, force the join by emulating the key.
2826                                 params.push_back(channel->key);
2827                         }
2828                         if (channel->GetUserCounter() > 1)
2829                         {
2830                                 // not the first in the channel
2831                                 DoOneToMany(user->nick,"JOIN",params);
2832                         }
2833                         else
2834                         {
2835                                 // first in the channel, set up their permissions
2836                                 // and the channel TS with FJOIN.
2837                                 char ts[24];
2838                                 snprintf(ts,24,"%lu",(unsigned long)channel->age);
2839                                 params.clear();
2840                                 params.push_back(channel->name);
2841                                 params.push_back(ts);
2842                                 params.push_back("@"+std::string(user->nick));
2843                                 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
2844                         }
2845                 }
2846         }
2847
2848         virtual void OnChangeHost(userrec* user, std::string newhost)
2849         {
2850                 // only occurs for local clients
2851                 if (user->registered != 7)
2852                         return;
2853                 std::deque<std::string> params;
2854                 params.push_back(newhost);
2855                 DoOneToMany(user->nick,"FHOST",params);
2856         }
2857
2858         virtual void OnChangeName(userrec* user, std::string gecos)
2859         {
2860                 // only occurs for local clients
2861                 if (user->registered != 7)
2862                         return;
2863                 std::deque<std::string> params;
2864                 params.push_back(gecos);
2865                 DoOneToMany(user->nick,"FNAME",params);
2866         }
2867
2868         virtual void OnUserPart(userrec* user, chanrec* channel)
2869         {
2870                 if (user->fd > -1)
2871                 {
2872                         std::deque<std::string> params;
2873                         params.push_back(channel->name);
2874                         DoOneToMany(user->nick,"PART",params);
2875                 }
2876         }
2877
2878         virtual void OnUserConnect(userrec* user)
2879         {
2880                 char agestr[MAXBUF];
2881                 if (user->fd > -1)
2882                 {
2883                         std::deque<std::string> params;
2884                         snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
2885                         params.push_back(agestr);
2886                         params.push_back(user->nick);
2887                         params.push_back(user->host);
2888                         params.push_back(user->dhost);
2889                         params.push_back(user->ident);
2890                         params.push_back("+"+std::string(user->modes));
2891                         params.push_back(user->ip);
2892                         params.push_back(":"+std::string(user->fullname));
2893                         DoOneToMany(Srv->GetServerName(),"NICK",params);
2894                 }
2895         }
2896
2897         virtual void OnUserQuit(userrec* user, std::string reason)
2898         {
2899                 if ((user->fd > -1) && (user->registered == 7))
2900                 {
2901                         std::deque<std::string> params;
2902                         params.push_back(":"+reason);
2903                         DoOneToMany(user->nick,"QUIT",params);
2904                 }
2905         }
2906
2907         virtual void OnUserPostNick(userrec* user, std::string oldnick)
2908         {
2909                 if (user->fd > -1)
2910                 {
2911                         std::deque<std::string> params;
2912                         params.push_back(user->nick);
2913                         DoOneToMany(oldnick,"NICK",params);
2914                 }
2915         }
2916
2917         virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
2918         {
2919                 if (source->fd > -1)
2920                 {
2921                         std::deque<std::string> params;
2922                         params.push_back(chan->name);
2923                         params.push_back(user->nick);
2924                         params.push_back(":"+reason);
2925                         DoOneToMany(source->nick,"KICK",params);
2926                 }
2927         }
2928
2929         virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
2930         {
2931                 std::deque<std::string> params;
2932                 params.push_back(dest->nick);
2933                 params.push_back(":"+reason);
2934                 DoOneToMany(source->nick,"KILL",params);
2935         }
2936
2937         virtual void OnRehash(std::string parameter)
2938         {
2939                 if (parameter != "")
2940                 {
2941                         std::deque<std::string> params;
2942                         params.push_back(parameter);
2943                         DoOneToMany(Srv->GetServerName(),"REHASH",params);
2944                         // check for self
2945                         if (Srv->MatchText(Srv->GetServerName(),parameter))
2946                         {
2947                                 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
2948                                 Srv->RehashServer();
2949                         }
2950                 }
2951                 ReadConfiguration(false);
2952         }
2953
2954         // note: the protocol does not allow direct umode +o except
2955         // via NICK with 8 params. sending OPERTYPE infers +o modechange
2956         // locally.
2957         virtual void OnOper(userrec* user, std::string opertype)
2958         {
2959                 if (user->fd > -1)
2960                 {
2961                         std::deque<std::string> params;
2962                         params.push_back(opertype);
2963                         DoOneToMany(user->nick,"OPERTYPE",params);
2964                 }
2965         }
2966
2967         void OnLine(userrec* source, std::string host, bool adding, char linetype, long duration, std::string reason)
2968         {
2969                 if (source->fd > -1)
2970                 {
2971                         char type[8];
2972                         snprintf(type,8,"%cLINE",linetype);
2973                         std::string stype = type;
2974                         if (adding)
2975                         {
2976                                 char sduration[MAXBUF];
2977                                 snprintf(sduration,MAXBUF,"%ld",duration);
2978                                 std::deque<std::string> params;
2979                                 params.push_back(host);
2980                                 params.push_back(sduration);
2981                                 params.push_back(":"+reason);
2982                                 DoOneToMany(source->nick,stype,params);
2983                         }
2984                         else
2985                         {
2986                                 std::deque<std::string> params;
2987                                 params.push_back(host);
2988                                 DoOneToMany(source->nick,stype,params);
2989                         }
2990                 }
2991         }
2992
2993         virtual void OnAddGLine(long duration, userrec* source, std::string reason, std::string hostmask)
2994         {
2995                 OnLine(source,hostmask,true,'G',duration,reason);
2996         }
2997         
2998         virtual void OnAddZLine(long duration, userrec* source, std::string reason, std::string ipmask)
2999         {
3000                 OnLine(source,ipmask,true,'Z',duration,reason);
3001         }
3002
3003         virtual void OnAddQLine(long duration, userrec* source, std::string reason, std::string nickmask)
3004         {
3005                 OnLine(source,nickmask,true,'Q',duration,reason);
3006         }
3007
3008         virtual void OnAddELine(long duration, userrec* source, std::string reason, std::string hostmask)
3009         {
3010                 OnLine(source,hostmask,true,'E',duration,reason);
3011         }
3012
3013         virtual void OnDelGLine(userrec* source, std::string hostmask)
3014         {
3015                 OnLine(source,hostmask,false,'G',0,"");
3016         }
3017
3018         virtual void OnDelZLine(userrec* source, std::string ipmask)
3019         {
3020                 OnLine(source,ipmask,false,'Z',0,"");
3021         }
3022
3023         virtual void OnDelQLine(userrec* source, std::string nickmask)
3024         {
3025                 OnLine(source,nickmask,false,'Q',0,"");
3026         }
3027
3028         virtual void OnDelELine(userrec* source, std::string hostmask)
3029         {
3030                 OnLine(source,hostmask,false,'E',0,"");
3031         }
3032
3033         virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
3034         {
3035                 if ((user->fd > -1) && (user->registered == 7))
3036                 {
3037                         if (target_type == TYPE_USER)
3038                         {
3039                                 userrec* u = (userrec*)dest;
3040                                 std::deque<std::string> params;
3041                                 params.push_back(u->nick);
3042                                 params.push_back(text);
3043                                 DoOneToMany(user->nick,"MODE",params);
3044                         }
3045                         else
3046                         {
3047                                 chanrec* c = (chanrec*)dest;
3048                                 std::deque<std::string> params;
3049                                 params.push_back(c->name);
3050                                 params.push_back(text);
3051                                 DoOneToMany(user->nick,"MODE",params);
3052                         }
3053                 }
3054         }
3055
3056         virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
3057         {
3058                 TreeSocket* s = (TreeSocket*)opaque;
3059                 if (target)
3060                 {
3061                         if (target_type == TYPE_USER)
3062                         {
3063                                 userrec* u = (userrec*)target;
3064                                 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
3065                         }
3066                         else
3067                         {
3068                                 chanrec* c = (chanrec*)target;
3069                                 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
3070                         }
3071                 }
3072         }
3073
3074         virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, std::string extname, std::string extdata)
3075         {
3076                 TreeSocket* s = (TreeSocket*)opaque;
3077                 if (target)
3078                 {
3079                         if (target_type == TYPE_USER)
3080                         {
3081                                 userrec* u = (userrec*)target;
3082                                 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+u->nick+" "+extname+" :"+extdata);
3083                         }
3084                         else
3085                         {
3086                                 chanrec* c = (chanrec*)target;
3087                                 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+c->name+" "+extname+" :"+extdata);
3088                         }
3089                 }
3090         }
3091
3092         virtual ~ModuleSpanningTree()
3093         {
3094         }
3095
3096         virtual Version GetVersion()
3097         {
3098                 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
3099         }
3100 };
3101
3102
3103 class ModuleSpanningTreeFactory : public ModuleFactory
3104 {
3105  public:
3106         ModuleSpanningTreeFactory()
3107         {
3108         }
3109         
3110         ~ModuleSpanningTreeFactory()
3111         {
3112         }
3113         
3114         virtual Module * CreateModule(Server* Me)
3115         {
3116                 TreeProtocolModule = new ModuleSpanningTree(Me);
3117                 return TreeProtocolModule;
3118         }
3119         
3120 };
3121
3122
3123 extern "C" void * init_module( void )
3124 {
3125         return new ModuleSpanningTreeFactory;
3126 }