]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree.cpp
Allowed capab unencrypted in an encrypted connection
[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 + CAPAB is still allowed unencryped */
1234                                         if ((ret.substr(0,7) != "ERROR :") && (ret.substr(0,6) != "CAPAB "))
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[10240];
1260                         char result64[10240];
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                         unsigned int ll = line.length();
1270                         log(DEBUG,"Plaintext line with padding = %d chars",ll);
1271                         ctx->Encrypt(line.c_str(), result, ll, 0);
1272                         log(DEBUG,"Encrypted.");
1273                         to64frombits((unsigned char*)result64,
1274                                         (unsigned char*)result,
1275                                         ll);
1276                         line = result64;
1277                         log(DEBUG,"Encrypted: %s",line.c_str());
1278                         //int from64tobits(char *out, const char *in, int maxlen);
1279                 }
1280                 return this->Write(line + "\r\n");
1281         }
1282
1283         /* Handle ERROR command */
1284         bool Error(std::deque<std::string> params)
1285         {
1286                 if (params.size() < 1)
1287                         return false;
1288                 std::string Errmsg = params[0];
1289                 std::string SName = myhost;
1290                 if (InboundServerName != "")
1291                 {
1292                         SName = InboundServerName;
1293                 }
1294                 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
1295                 /* we will return false to cause the socket to close.
1296                  */
1297                 return false;
1298         }
1299
1300         /* Because the core won't let users or even SERVERS set +o,
1301          * we use the OPERTYPE command to do this.
1302          */
1303         bool OperType(std::string prefix, std::deque<std::string> &params)
1304         {
1305                 if (params.size() != 1)
1306                         return true;
1307                 std::string opertype = params[0];
1308                 userrec* u = Srv->FindNick(prefix);
1309                 if (u)
1310                 {
1311                         strlcpy(u->oper,opertype.c_str(),NICKMAX);
1312                         if (!strchr(u->modes,'o'))
1313                         {
1314                                 strcat(u->modes,"o");
1315                         }
1316                         DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
1317                 }
1318                 return true;
1319         }
1320
1321         /* Because Andy insists that services-compatible servers must
1322          * implement SVSNICK and SVSJOIN, that's exactly what we do :p
1323          */
1324         bool ForceNick(std::string prefix, std::deque<std::string> &params)
1325         {
1326                 if (params.size() < 3)
1327                         return true;
1328                 userrec* u = Srv->FindNick(params[0]);
1329                 if (u)
1330                 {
1331                         Srv->ChangeUserNick(u,params[1]);
1332                         u->age = atoi(params[2].c_str());
1333                         DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
1334                 }
1335                 return true;
1336         }
1337
1338         bool ServiceJoin(std::string prefix, std::deque<std::string> &params)
1339         {
1340                 if (params.size() < 2)
1341                         return true;
1342                 userrec* u = Srv->FindNick(params[0]);
1343                 if (u)
1344                 {
1345                         Srv->JoinUserToChannel(u,params[1],"");
1346                         DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
1347                 }
1348                 return true;
1349         }
1350
1351         bool RemoteRehash(std::string prefix, std::deque<std::string> &params)
1352         {
1353                 if (params.size() < 1)
1354                         return false;
1355                 std::string servermask = params[0];
1356                 if (Srv->MatchText(Srv->GetServerName(),servermask))
1357                 {
1358                         Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
1359                         Srv->RehashServer();
1360                         ReadConfiguration(false);
1361                 }
1362                 DoOneToAllButSender(prefix,"REHASH",params,prefix);
1363                 return true;
1364         }
1365
1366         bool RemoteKill(std::string prefix, std::deque<std::string> &params)
1367         {
1368                 if (params.size() != 2)
1369                         return true;
1370                 std::string nick = params[0];
1371                 userrec* u = Srv->FindNick(prefix);
1372                 userrec* who = Srv->FindNick(nick);
1373                 if (who)
1374                 {
1375                         /* Prepend kill source, if we don't have one */
1376                         std::string sourceserv = prefix;
1377                         if (u)
1378                         {
1379                                 sourceserv = u->server;
1380                         }
1381                         if (*(params[1].c_str()) != '[')
1382                         {
1383                                 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
1384                         }
1385                         std::string reason = params[1];
1386                         params[1] = ":" + params[1];
1387                         DoOneToAllButSender(prefix,"KILL",params,sourceserv);
1388                         Srv->QuitUser(who,reason);
1389                 }
1390                 return true;
1391         }
1392
1393         bool LocalPong(std::string prefix, std::deque<std::string> &params)
1394         {
1395                 if (params.size() < 1)
1396                         return true;
1397                 TreeServer* ServerSource = FindServer(prefix);
1398                 if (ServerSource)
1399                 {
1400                         ServerSource->SetPingFlag();
1401                 }
1402                 return true;
1403         }
1404         
1405         bool MetaData(std::string prefix, std::deque<std::string> &params)
1406         {
1407                 if (params.size() < 3)
1408                         return true;
1409                 TreeServer* ServerSource = FindServer(prefix);
1410                 if (ServerSource)
1411                 {
1412                         if (*(params[0].c_str()) == '#')
1413                         {
1414                                 chanrec* c = Srv->FindChannel(params[0]);
1415                                 if (c)
1416                                 {
1417                                         FOREACH_MOD OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]);
1418                                 }
1419                         }
1420                         else
1421                         {
1422                                 userrec* u = Srv->FindNick(params[0]);
1423                                 if (u)
1424                                 {
1425                                         FOREACH_MOD OnDecodeMetaData(TYPE_USER,u,params[1],params[2]);
1426                                 }
1427                         }
1428                 }
1429                 params[2] = ":" + params[2];
1430                 DoOneToAllButSender(prefix,"METADATA",params,prefix);
1431                 return true;
1432         }
1433
1434         bool ServerVersion(std::string prefix, std::deque<std::string> &params)
1435         {
1436                 if (params.size() < 1)
1437                         return true;
1438                 TreeServer* ServerSource = FindServer(prefix);
1439                 if (ServerSource)
1440                 {
1441                         ServerSource->SetVersion(params[0]);
1442                 }
1443                 params[0] = ":" + params[0];
1444                 DoOneToAllButSender(prefix,"VERSION",params,prefix);
1445                 return true;
1446         }
1447
1448         bool ChangeHost(std::string prefix, std::deque<std::string> &params)
1449         {
1450                 if (params.size() < 1)
1451                         return true;
1452                 userrec* u = Srv->FindNick(prefix);
1453                 if (u)
1454                 {
1455                         Srv->ChangeHost(u,params[0]);
1456                         DoOneToAllButSender(prefix,"FHOST",params,u->server);
1457                 }
1458                 return true;
1459         }
1460
1461         bool AddLine(std::string prefix, std::deque<std::string> &params)
1462         {
1463                 if (params.size() < 6)
1464                         return true;
1465                 std::string linetype = params[0]; /* Z, Q, E, G, K */
1466                 std::string mask = params[1]; /* Line type dependent */
1467                 std::string source = params[2]; /* may not be online or may be a server */
1468                 std::string settime = params[3]; /* EPOCH time set */
1469                 std::string duration = params[4]; /* Duration secs */
1470                 std::string reason = params[5];
1471
1472                 switch (*(linetype.c_str()))
1473                 {
1474                         case 'Z':
1475                                 add_zline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1476                                 zline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1477                         break;
1478                         case 'Q':
1479                                 add_qline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1480                                 qline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1481                         break;
1482                         case 'E':
1483                                 add_eline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1484                                 eline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1485                         break;
1486                         case 'G':
1487                                 add_gline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1488                                 gline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1489                         break;
1490                         case 'K':
1491                                 add_kline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1492                         break;
1493                         default:
1494                                 /* Just in case... */
1495                                 Srv->SendOpers("*** \2WARNING\2: Invalid xline type '"+linetype+"' sent by server "+prefix+", ignored!");
1496                         break;
1497                 }
1498                 /* Send it on its way */
1499                 params[5] = ":" + params[5];
1500                 DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
1501                 return true;
1502         }
1503
1504         bool ChangeName(std::string prefix, std::deque<std::string> &params)
1505         {
1506                 if (params.size() < 1)
1507                         return true;
1508                 userrec* u = Srv->FindNick(prefix);
1509                 if (u)
1510                 {
1511                         Srv->ChangeGECOS(u,params[0]);
1512                         params[0] = ":" + params[0];
1513                         DoOneToAllButSender(prefix,"FNAME",params,u->server);
1514                 }
1515                 return true;
1516         }
1517
1518         bool Whois(std::string prefix, std::deque<std::string> &params)
1519         {
1520                 if (params.size() < 1)
1521                         return true;
1522                 log(DEBUG,"In IDLE command");
1523                 userrec* u = Srv->FindNick(prefix);
1524                 if (u)
1525                 {
1526                         log(DEBUG,"USER EXISTS: %s",u->nick);
1527                         // an incoming request
1528                         if (params.size() == 1)
1529                         {
1530                                 userrec* x = Srv->FindNick(params[0]);
1531                                 if (x->fd > -1)
1532                                 {
1533                                         userrec* x = Srv->FindNick(params[0]);
1534                                         log(DEBUG,"Got IDLE");
1535                                         char signon[MAXBUF];
1536                                         char idle[MAXBUF];
1537                                         log(DEBUG,"Sending back IDLE 3");
1538                                         snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
1539                                         snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-time(NULL)));
1540                                         std::deque<std::string> par;
1541                                         par.push_back(prefix);
1542                                         par.push_back(signon);
1543                                         par.push_back(idle);
1544                                         // ours, we're done, pass it BACK
1545                                         DoOneToOne(params[0],"IDLE",par,u->server);
1546                                 }
1547                                 else
1548                                 {
1549                                         // not ours pass it on
1550                                         DoOneToOne(prefix,"IDLE",params,x->server);
1551                                 }
1552                         }
1553                         else if (params.size() == 3)
1554                         {
1555                                 std::string who_did_the_whois = params[0];
1556                                 userrec* who_to_send_to = Srv->FindNick(who_did_the_whois);
1557                                 if (who_to_send_to->fd > -1)
1558                                 {
1559                                         log(DEBUG,"Got final IDLE");
1560                                         // an incoming reply to a whois we sent out
1561                                         std::string nick_whoised = prefix;
1562                                         unsigned long signon = atoi(params[1].c_str());
1563                                         unsigned long idle = atoi(params[2].c_str());
1564                                         if ((who_to_send_to) && (who_to_send_to->fd > -1))
1565                                                 do_whois(who_to_send_to,u,signon,idle,(char*)nick_whoised.c_str());
1566                                 }
1567                                 else
1568                                 {
1569                                         // not ours, pass it on
1570                                         DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
1571                                 }
1572                         }
1573                 }
1574                 return true;
1575         }
1576         
1577         bool LocalPing(std::string prefix, std::deque<std::string> &params)
1578         {
1579                 if (params.size() < 1)
1580                         return true;
1581                 std::string stufftobounce = params[0];
1582                 this->WriteLine(":"+Srv->GetServerName()+" PONG "+stufftobounce);
1583                 return true;
1584         }
1585
1586         bool RemoteServer(std::string prefix, std::deque<std::string> &params)
1587         {
1588                 if (params.size() < 4)
1589                         return false;
1590                 std::string servername = params[0];
1591                 std::string password = params[1];
1592                 // hopcount is not used for a remote server, we calculate this ourselves
1593                 std::string description = params[3];
1594                 TreeServer* ParentOfThis = FindServer(prefix);
1595                 if (!ParentOfThis)
1596                 {
1597                         this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
1598                         return false;
1599                 }
1600                 TreeServer* CheckDupe = FindServer(servername);
1601                 if (CheckDupe)
1602                 {
1603                         this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1604                         Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1605                         return false;
1606                 }
1607                 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
1608                 ParentOfThis->AddChild(Node);
1609                 params[3] = ":" + params[3];
1610                 DoOneToAllButSender(prefix,"SERVER",params,prefix);
1611                 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
1612                 return true;
1613         }
1614
1615         bool Outbound_Reply_Server(std::deque<std::string> &params)
1616         {
1617                 if (params.size() < 4)
1618                         return false;
1619                 std::string servername = params[0];
1620                 std::string password = params[1];
1621                 int hops = atoi(params[2].c_str());
1622                 if (hops)
1623                 {
1624                         this->WriteLine("ERROR :Server too far away for authentication");
1625                         Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, server is too far away for authentication");
1626                         return false;
1627                 }
1628                 std::string description = params[3];
1629                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1630                 {
1631                         if ((x->Name == servername) && (x->RecvPass == password))
1632                         {
1633                                 TreeServer* CheckDupe = FindServer(servername);
1634                                 if (CheckDupe)
1635                                 {
1636                                         this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1637                                         Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1638                                         return false;
1639                                 }
1640                                 // Begin the sync here. this kickstarts the
1641                                 // other side, waiting in WAIT_AUTH_2 state,
1642                                 // into starting their burst, as it shows
1643                                 // that we're happy.
1644                                 this->LinkState = CONNECTED;
1645                                 // we should add the details of this server now
1646                                 // to the servers tree, as a child of the root
1647                                 // node.
1648                                 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
1649                                 TreeRoot->AddChild(Node);
1650                                 params[3] = ":" + params[3];
1651                                 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
1652                                 this->bursting = true;
1653                                 this->DoBurst(Node);
1654                                 return true;
1655                         }
1656                 }
1657                 this->WriteLine("ERROR :Invalid credentials");
1658                 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, invalid link credentials");
1659                 return false;
1660         }
1661
1662         bool Inbound_Server(std::deque<std::string> &params)
1663         {
1664                 if (params.size() < 4)
1665                         return false;
1666                 std::string servername = params[0];
1667                 std::string password = params[1];
1668                 int hops = atoi(params[2].c_str());
1669                 if (hops)
1670                 {
1671                         this->WriteLine("ERROR :Server too far away for authentication");
1672                         Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, server is too far away for authentication");
1673                         return false;
1674                 }
1675                 std::string description = params[3];
1676                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1677                 {
1678                         if ((x->Name == servername) && (x->RecvPass == password))
1679                         {
1680                                 TreeServer* CheckDupe = FindServer(servername);
1681                                 if (CheckDupe)
1682                                 {
1683                                         this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1684                                         Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1685                                         return false;
1686                                 }
1687                                 /* If the config says this link is encrypted, but the remote side
1688                                  * hasnt bothered to send the AES command before SERVER, then we
1689                                  * boot them off as we MUST have this connection encrypted.
1690                                  */
1691                                 if ((x->EncryptionKey != "") && (!this->ctx))
1692                                 {
1693                                         this->WriteLine("ERROR :This link requires AES encryption to be enabled. Plaintext connection refused.");
1694                                         Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, remote server did not enable AES.");
1695                                         return false;
1696                                 }
1697                                 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
1698                                 this->InboundServerName = servername;
1699                                 this->InboundDescription = description;
1700                                 // this is good. Send our details: Our server name and description and hopcount of 0,
1701                                 // along with the sendpass from this block.
1702                                 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
1703                                 // move to the next state, we are now waiting for THEM.
1704                                 this->LinkState = WAIT_AUTH_2;
1705                                 return true;
1706                         }
1707                 }
1708                 this->WriteLine("ERROR :Invalid credentials");
1709                 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, invalid link credentials");
1710                 return false;
1711         }
1712
1713         void Split(std::string line, bool stripcolon, std::deque<std::string> &n)
1714         {
1715                 if (!strchr(line.c_str(),' '))
1716                 {
1717                         n.push_back(line);
1718                         return;
1719                 }
1720                 std::stringstream s(line);
1721                 std::string param = "";
1722                 n.clear();
1723                 int item = 0;
1724                 while (!s.eof())
1725                 {
1726                         char c;
1727                         s.get(c);
1728                         if (c == ' ')
1729                         {
1730                                 n.push_back(param);
1731                                 param = "";
1732                                 item++;
1733                         }
1734                         else
1735                         {
1736                                 if (!s.eof())
1737                                 {
1738                                         param = param + c;
1739                                 }
1740                                 if ((param == ":") && (item > 0))
1741                                 {
1742                                         param = "";
1743                                         while (!s.eof())
1744                                         {
1745                                                 s.get(c);
1746                                                 if (!s.eof())
1747                                                 {
1748                                                         param = param + c;
1749                                                 }
1750                                         }
1751                                         n.push_back(param);
1752                                         param = "";
1753                                 }
1754                         }
1755                 }
1756                 if (param != "")
1757                 {
1758                         n.push_back(param);
1759                 }
1760                 return;
1761         }
1762
1763         bool ProcessLine(std::string line)
1764         {
1765                 char* l = (char*)line.c_str();
1766                 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
1767                         l[strlen(l)-1] = '\0';
1768                 line = l;
1769                 if (line == "")
1770                         return true;
1771                 Srv->Log(DEBUG,"IN: "+line);
1772                 std::deque<std::string> params;
1773                 this->Split(line,true,params);
1774                 std::string command = "";
1775                 std::string prefix = "";
1776                 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
1777                 {
1778                         prefix = params[0];
1779                         command = params[1];
1780                         char* pref = (char*)prefix.c_str();
1781                         prefix = ++pref;
1782                         params.pop_front();
1783                         params.pop_front();
1784                 }
1785                 else
1786                 {
1787                         prefix = "";
1788                         command = params[0];
1789                         params.pop_front();
1790                 }
1791
1792                 if ((!this->ctx) && (command == "AES"))
1793                 {
1794                         std::string sserv = params[0];
1795                         for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1796                         {
1797                                 if ((x->EncryptionKey != "") && (x->Name == sserv))
1798                                 {
1799                                         this->InitAES(x->EncryptionKey,sserv);
1800                                 }
1801                         }
1802                         return true;
1803                 }
1804                 else if ((this->ctx) && (command == "AES"))
1805                 {
1806                         WriteOpers("*** \2AES\2: Encryption already enabled on this connection yet %s is trying to enable it twice!",params[0].c_str());
1807                 }
1808
1809                 switch (this->LinkState)
1810                 {
1811                         TreeServer* Node;
1812                         
1813                         case WAIT_AUTH_1:
1814                                 // Waiting for SERVER command from remote server. Server initiating
1815                                 // the connection sends the first SERVER command, listening server
1816                                 // replies with theirs if its happy, then if the initiator is happy,
1817                                 // it starts to send its net sync, which starts the merge, otherwise
1818                                 // it sends an ERROR.
1819                                 if (command == "PASS")
1820                                 {
1821                                         /* Silently ignored */
1822                                 }
1823                                 else if (command == "SERVER")
1824                                 {
1825                                         return this->Inbound_Server(params);
1826                                 }
1827                                 else if (command == "ERROR")
1828                                 {
1829                                         return this->Error(params);
1830                                 }
1831                                 else if (command == "USER")
1832                                 {
1833                                         this->WriteLine("ERROR :Client connections to this port are prohibited.");
1834                                         return false;
1835                                 }
1836                                 else if (command == "CAPAB")
1837                                 {
1838                                         return this->Capab(params);
1839                                 }
1840                                 else
1841                                 {
1842                                         this->WriteLine("ERROR :Invalid command in negotiation phase.");
1843                                         return false;
1844                                 }
1845                         break;
1846                         case WAIT_AUTH_2:
1847                                 // Waiting for start of other side's netmerge to say they liked our
1848                                 // password.
1849                                 if (command == "SERVER")
1850                                 {
1851                                         // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1852                                         // silently ignore.
1853                                         return true;
1854                                 }
1855                                 else if (command == "BURST")
1856                                 {
1857                                         this->LinkState = CONNECTED;
1858                                         Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
1859                                         TreeRoot->AddChild(Node);
1860                                         params.clear();
1861                                         params.push_back(InboundServerName);
1862                                         params.push_back("*");
1863                                         params.push_back("1");
1864                                         params.push_back(":"+InboundDescription);
1865                                         DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
1866                                         this->bursting = true;
1867                                         this->DoBurst(Node);
1868                                 }
1869                                 else if (command == "ERROR")
1870                                 {
1871                                         return this->Error(params);
1872                                 }
1873                                 else if (command == "CAPAB")
1874                                 {
1875                                         return this->Capab(params);
1876                                 }
1877                                 
1878                         break;
1879                         case LISTENER:
1880                                 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
1881                                 return false;
1882                         break;
1883                         case CONNECTING:
1884                                 if (command == "SERVER")
1885                                 {
1886                                         // another server we connected to, which was in WAIT_AUTH_1 state,
1887                                         // has just sent us their credentials. If we get this far, theyre
1888                                         // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1889                                         // if we're happy with this, we should send our netburst which
1890                                         // kickstarts the merge.
1891                                         return this->Outbound_Reply_Server(params);
1892                                 }
1893                                 else if (command == "ERROR")
1894                                 {
1895                                         return this->Error(params);
1896                                 }
1897                         break;
1898                         case CONNECTED:
1899                                 // This is the 'authenticated' state, when all passwords
1900                                 // have been exchanged and anything past this point is taken
1901                                 // as gospel.
1902                                 
1903                                 if (prefix != "")
1904                                 {
1905                                         std::string direction = prefix;
1906                                         userrec* t = Srv->FindNick(prefix);
1907                                         if (t)
1908                                         {
1909                                                 direction = t->server;
1910                                         }
1911                                         TreeServer* route_back_again = BestRouteTo(direction);
1912                                         if ((!route_back_again) || (route_back_again->GetSocket() != this))
1913                                         {
1914                                                 if (route_back_again)
1915                                                 {
1916                                                         WriteOpers("*** Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
1917                                                 }
1918                                                 else
1919                                                 {
1920                                                         WriteOpers("*** Protocol violation: Invalid source '%s' in command '%s' from connection '%s'",direction.c_str(),line.c_str(),this->GetName().c_str());
1921                                                 }
1922                                                 
1923                                                 return true;
1924                                         }
1925                                 }
1926                                 
1927                                 if (command == "SVSMODE")
1928                                 {
1929                                         /* Services expects us to implement
1930                                          * SVSMODE. In inspircd its the same as
1931                                          * MODE anyway.
1932                                          */
1933                                         command = "MODE";
1934                                 }
1935                                 std::string target = "";
1936                                 /* Yes, know, this is a mess. Its reasonably fast though as we're
1937                                  * working with std::string here.
1938                                  */
1939                                 if ((command == "NICK") && (params.size() > 1))
1940                                 {
1941                                         return this->IntroduceClient(prefix,params);
1942                                 }
1943                                 else if (command == "FJOIN")
1944                                 {
1945                                         return this->ForceJoin(prefix,params);
1946                                 }
1947                                 else if (command == "SERVER")
1948                                 {
1949                                         return this->RemoteServer(prefix,params);
1950                                 }
1951                                 else if (command == "ERROR")
1952                                 {
1953                                         return this->Error(params);
1954                                 }
1955                                 else if (command == "OPERTYPE")
1956                                 {
1957                                         return this->OperType(prefix,params);
1958                                 }
1959                                 else if (command == "FMODE")
1960                                 {
1961                                         return this->ForceMode(prefix,params);
1962                                 }
1963                                 else if (command == "KILL")
1964                                 {
1965                                         return this->RemoteKill(prefix,params);
1966                                 }
1967                                 else if (command == "FTOPIC")
1968                                 {
1969                                         return this->ForceTopic(prefix,params);
1970                                 }
1971                                 else if (command == "REHASH")
1972                                 {
1973                                         return this->RemoteRehash(prefix,params);
1974                                 }
1975                                 else if (command == "METADATA")
1976                                 {
1977                                         return this->MetaData(prefix,params);
1978                                 }
1979                                 else if (command == "PING")
1980                                 {
1981                                         return this->LocalPing(prefix,params);
1982                                 }
1983                                 else if (command == "PONG")
1984                                 {
1985                                         return this->LocalPong(prefix,params);
1986                                 }
1987                                 else if (command == "VERSION")
1988                                 {
1989                                         return this->ServerVersion(prefix,params);
1990                                 }
1991                                 else if (command == "FHOST")
1992                                 {
1993                                         return this->ChangeHost(prefix,params);
1994                                 }
1995                                 else if (command == "FNAME")
1996                                 {
1997                                         return this->ChangeName(prefix,params);
1998                                 }
1999                                 else if (command == "ADDLINE")
2000                                 {
2001                                         return this->AddLine(prefix,params);
2002                                 }
2003                                 else if (command == "SVSNICK")
2004                                 {
2005                                         if (prefix == "")
2006                                         {
2007                                                 prefix = this->GetName();
2008                                         }
2009                                         return this->ForceNick(prefix,params);
2010                                 }
2011                                 else if (command == "IDLE")
2012                                 {
2013                                         return this->Whois(prefix,params);
2014                                 }
2015                                 else if (command == "SVSJOIN")
2016                                 {
2017                                         if (prefix == "")
2018                                         {
2019                                                 prefix = this->GetName();
2020                                         }
2021                                         return this->ServiceJoin(prefix,params);
2022                                 }
2023                                 else if (command == "SQUIT")
2024                                 {
2025                                         if (params.size() == 2)
2026                                         {
2027                                                 this->Squit(FindServer(params[0]),params[1]);
2028                                         }
2029                                         return true;
2030                                 }
2031                                 else if (command == "ENDBURST")
2032                                 {
2033                                         this->bursting = false;
2034                                         return true;
2035                                 }
2036                                 else
2037                                 {
2038                                         // not a special inter-server command.
2039                                         // Emulate the actual user doing the command,
2040                                         // this saves us having a huge ugly parser.
2041                                         userrec* who = Srv->FindNick(prefix);
2042                                         std::string sourceserv = this->myhost;
2043                                         if (this->InboundServerName != "")
2044                                         {
2045                                                 sourceserv = this->InboundServerName;
2046                                         }
2047                                         if (who)
2048                                         {
2049                                                 // its a user
2050                                                 target = who->server;
2051                                                 char* strparams[127];
2052                                                 for (unsigned int q = 0; q < params.size(); q++)
2053                                                 {
2054                                                         strparams[q] = (char*)params[q].c_str();
2055                                                 }
2056                                                 Srv->CallCommandHandler(command, strparams, params.size(), who);
2057                                         }
2058                                         else
2059                                         {
2060                                                 // its not a user. Its either a server, or somethings screwed up.
2061                                                 if (IsServer(prefix))
2062                                                 {
2063                                                         target = Srv->GetServerName();
2064                                                 }
2065                                                 else
2066                                                 {
2067                                                         log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
2068                                                         return true;
2069                                                 }
2070                                         }
2071                                         return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
2072
2073                                 }
2074                                 return true;
2075                         break;
2076                 }
2077                 return true;
2078         }
2079
2080         virtual std::string GetName()
2081         {
2082                 std::string sourceserv = this->myhost;
2083                 if (this->InboundServerName != "")
2084                 {
2085                         sourceserv = this->InboundServerName;
2086                 }
2087                 return sourceserv;
2088         }
2089
2090         virtual void OnTimeout()
2091         {
2092                 if (this->LinkState == CONNECTING)
2093                 {
2094                         Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
2095                 }
2096         }
2097
2098         virtual void OnClose()
2099         {
2100                 // Connection closed.
2101                 // If the connection is fully up (state CONNECTED)
2102                 // then propogate a netsplit to all peers.
2103                 std::string quitserver = this->myhost;
2104                 if (this->InboundServerName != "")
2105                 {
2106                         quitserver = this->InboundServerName;
2107                 }
2108                 TreeServer* s = FindServer(quitserver);
2109                 if (s)
2110                 {
2111                         Squit(s,"Remote host closed the connection");
2112                 }
2113                 WriteOpers("Server '\2%s\2[%s]' closed the connection.",quitserver.c_str(),this->GetIP().c_str());
2114         }
2115
2116         virtual int OnIncomingConnection(int newsock, char* ip)
2117         {
2118                 TreeSocket* s = new TreeSocket(newsock, ip);
2119                 Srv->AddSocket(s);
2120                 return true;
2121         }
2122 };
2123
2124 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
2125 {
2126         for (unsigned int c = 0; c < list.size(); c++)
2127         {
2128                 if (list[c] == server)
2129                 {
2130                         return;
2131                 }
2132         }
2133         list.push_back(server);
2134 }
2135
2136 // returns a list of DIRECT servernames for a specific channel
2137 void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
2138 {
2139         std::vector<char*> *ulist = c->GetUsers();
2140         unsigned int ucount = ulist->size();
2141         for (unsigned int i = 0; i < ucount; i++)
2142         {
2143                 char* o = (*ulist)[i];
2144                 userrec* otheruser = (userrec*)o;
2145                 if (otheruser->fd < 0)
2146                 {
2147                         TreeServer* best = BestRouteTo(otheruser->server);
2148                         if (best)
2149                                 AddThisServer(best,list);
2150                 }
2151         }
2152         return;
2153 }
2154
2155 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, std::string command, std::deque<std::string> &params)
2156 {
2157         TreeServer* omitroute = BestRouteTo(omit);
2158         if ((command == "NOTICE") || (command == "PRIVMSG"))
2159         {
2160                 if ((params.size() >= 2) && (*(params[0].c_str()) != '$'))
2161                 {
2162                         if (*(params[0].c_str()) != '#')
2163                         {
2164                                 // special routing for private messages/notices
2165                                 userrec* d = Srv->FindNick(params[0]);
2166                                 if (d)
2167                                 {
2168                                         std::deque<std::string> par;
2169                                         par.push_back(params[0]);
2170                                         par.push_back(":"+params[1]);
2171                                         DoOneToOne(prefix,command,par,d->server);
2172                                         return true;
2173                                 }
2174                         }
2175                         else
2176                         {
2177                                 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
2178                                 chanrec* c = Srv->FindChannel(params[0]);
2179                                 if (c)
2180                                 {
2181                                         std::deque<TreeServer*> list;
2182                                         GetListOfServersForChannel(c,list);
2183                                         log(DEBUG,"Got a list of %d servers",list.size());
2184                                         unsigned int lsize = list.size();
2185                                         for (unsigned int i = 0; i < lsize; i++)
2186                                         {
2187                                                 TreeSocket* Sock = list[i]->GetSocket();
2188                                                 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
2189                                                 {
2190                                                         log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
2191                                                         Sock->WriteLine(data);
2192                                                 }
2193                                         }
2194                                         return true;
2195                                 }
2196                         }
2197                 }
2198         }
2199         unsigned int items = TreeRoot->ChildCount();
2200         for (unsigned int x = 0; x < items; x++)
2201         {
2202                 TreeServer* Route = TreeRoot->GetChild(x);
2203                 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
2204                 {
2205                         TreeSocket* Sock = Route->GetSocket();
2206                         Sock->WriteLine(data);
2207                 }
2208         }
2209         return true;
2210 }
2211
2212 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> &params, std::string omit)
2213 {
2214         TreeServer* omitroute = BestRouteTo(omit);
2215         std::string FullLine = ":" + prefix + " " + command;
2216         unsigned int words = params.size();
2217         for (unsigned int x = 0; x < words; x++)
2218         {
2219                 FullLine = FullLine + " " + params[x];
2220         }
2221         unsigned int items = TreeRoot->ChildCount();
2222         for (unsigned int x = 0; x < items; x++)
2223         {
2224                 TreeServer* Route = TreeRoot->GetChild(x);
2225                 // Send the line IF:
2226                 // The route has a socket (its a direct connection)
2227                 // The route isnt the one to be omitted
2228                 // The route isnt the path to the one to be omitted
2229                 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
2230                 {
2231                         TreeSocket* Sock = Route->GetSocket();
2232                         Sock->WriteLine(FullLine);
2233                 }
2234         }
2235         return true;
2236 }
2237
2238 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> &params)
2239 {
2240         std::string FullLine = ":" + prefix + " " + command;
2241         unsigned int words = params.size();
2242         for (unsigned int x = 0; x < words; x++)
2243         {
2244                 FullLine = FullLine + " " + params[x];
2245         }
2246         unsigned int items = TreeRoot->ChildCount();
2247         for (unsigned int x = 0; x < items; x++)
2248         {
2249                 TreeServer* Route = TreeRoot->GetChild(x);
2250                 if (Route->GetSocket())
2251                 {
2252                         TreeSocket* Sock = Route->GetSocket();
2253                         Sock->WriteLine(FullLine);
2254                 }
2255         }
2256         return true;
2257 }
2258
2259 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> &params, std::string target)
2260 {
2261         TreeServer* Route = BestRouteTo(target);
2262         if (Route)
2263         {
2264                 std::string FullLine = ":" + prefix + " " + command;
2265                 unsigned int words = params.size();
2266                 for (unsigned int x = 0; x < words; x++)
2267                 {
2268                         FullLine = FullLine + " " + params[x];
2269                 }
2270                 if (Route->GetSocket())
2271                 {
2272                         TreeSocket* Sock = Route->GetSocket();
2273                         Sock->WriteLine(FullLine);
2274                 }
2275                 return true;
2276         }
2277         else
2278         {
2279                 return true;
2280         }
2281 }
2282
2283 std::vector<TreeSocket*> Bindings;
2284
2285 void ReadConfiguration(bool rebind)
2286 {
2287         Conf = new ConfigReader;
2288         if (rebind)
2289         {
2290                 for (int j =0; j < Conf->Enumerate("bind"); j++)
2291                 {
2292                         std::string Type = Conf->ReadValue("bind","type",j);
2293                         std::string IP = Conf->ReadValue("bind","address",j);
2294                         long Port = Conf->ReadInteger("bind","port",j,true);
2295                         if (Type == "servers")
2296                         {
2297                                 if (IP == "*")
2298                                 {
2299                                         IP = "";
2300                                 }
2301                                 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
2302                                 if (listener->GetState() == I_LISTENING)
2303                                 {
2304                                         Srv->AddSocket(listener);
2305                                         Bindings.push_back(listener);
2306                                 }
2307                                 else
2308                                 {
2309                                         log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
2310                                         listener->Close();
2311                                         delete listener;
2312                                 }
2313                         }
2314                 }
2315         }
2316         LinkBlocks.clear();
2317         for (int j =0; j < Conf->Enumerate("link"); j++)
2318         {
2319                 Link L;
2320                 L.Name = Conf->ReadValue("link","name",j);
2321                 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
2322                 L.Port = Conf->ReadInteger("link","port",j,true);
2323                 L.SendPass = Conf->ReadValue("link","sendpass",j);
2324                 L.RecvPass = Conf->ReadValue("link","recvpass",j);
2325                 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
2326                 L.EncryptionKey =  Conf->ReadValue("link","encryptionkey",j);
2327                 L.NextConnectTime = time(NULL) + L.AutoConnect;
2328                 /* Bugfix by brain, do not allow people to enter bad configurations */
2329                 if ((L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
2330                 {
2331                         LinkBlocks.push_back(L);
2332                         log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
2333                 }
2334                 else
2335                 {
2336                         log(DEFAULT,"m_spanningtree: Invalid configuration for server '%s', ignored!",L.Name.c_str());
2337                 }
2338         }
2339         delete Conf;
2340 }
2341
2342
2343 class ModuleSpanningTree : public Module
2344 {
2345         std::vector<TreeSocket*> Bindings;
2346         int line;
2347         int NumServers;
2348
2349  public:
2350
2351         ModuleSpanningTree(Server* Me)
2352                 : Module::Module(Me)
2353         {
2354                 Srv = Me;
2355                 Bindings.clear();
2356
2357                 // Create the root of the tree
2358                 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
2359
2360                 ReadConfiguration(true);
2361         }
2362
2363         void ShowLinks(TreeServer* Current, userrec* user, int hops)
2364         {
2365                 std::string Parent = TreeRoot->GetName();
2366                 if (Current->GetParent())
2367                 {
2368                         Parent = Current->GetParent()->GetName();
2369                 }
2370                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
2371                 {
2372                         ShowLinks(Current->GetChild(q),user,hops+1);
2373                 }
2374                 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
2375         }
2376
2377         int CountLocalServs()
2378         {
2379                 return TreeRoot->ChildCount();
2380         }
2381
2382         int CountServs()
2383         {
2384                 return serverlist.size();
2385         }
2386
2387         void HandleLinks(char** parameters, int pcnt, userrec* user)
2388         {
2389                 ShowLinks(TreeRoot,user,0);
2390                 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
2391                 return;
2392         }
2393
2394         void HandleLusers(char** parameters, int pcnt, userrec* user)
2395         {
2396                 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),this->CountServs());
2397                 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
2398                 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
2399                 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
2400                 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
2401                 return;
2402         }
2403
2404         // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
2405
2406         void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
2407         {
2408                 if (line < 128)
2409                 {
2410                         for (int t = 0; t < depth; t++)
2411                         {
2412                                 matrix[line][t] = ' ';
2413                         }
2414                         strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
2415                         line++;
2416                         for (unsigned int q = 0; q < Current->ChildCount(); q++)
2417                         {
2418                                 ShowMap(Current->GetChild(q),user,depth+2,matrix);
2419                         }
2420                 }
2421         }
2422
2423         // Ok, prepare to be confused.
2424         // After much mulling over how to approach this, it struck me that
2425         // the 'usual' way of doing a /MAP isnt the best way. Instead of
2426         // keeping track of a ton of ascii characters, and line by line
2427         // under recursion working out where to place them using multiplications
2428         // and divisons, we instead render the map onto a backplane of characters
2429         // (a character matrix), then draw the branches as a series of "L" shapes
2430         // from the nodes. This is not only friendlier on CPU it uses less stack.
2431
2432         void HandleMap(char** parameters, int pcnt, userrec* user)
2433         {
2434                 // This array represents a virtual screen which we will
2435                 // "scratch" draw to, as the console device of an irc
2436                 // client does not provide for a proper terminal.
2437                 char matrix[128][80];
2438                 for (unsigned int t = 0; t < 128; t++)
2439                 {
2440                         matrix[t][0] = '\0';
2441                 }
2442                 line = 0;
2443                 // The only recursive bit is called here.
2444                 ShowMap(TreeRoot,user,0,matrix);
2445                 // Process each line one by one. The algorithm has a limit of
2446                 // 128 servers (which is far more than a spanning tree should have
2447                 // anyway, so we're ok). This limit can be raised simply by making
2448                 // the character matrix deeper, 128 rows taking 10k of memory.
2449                 for (int l = 1; l < line; l++)
2450                 {
2451                         // scan across the line looking for the start of the
2452                         // servername (the recursive part of the algorithm has placed
2453                         // the servers at indented positions depending on what they
2454                         // are related to)
2455                         int first_nonspace = 0;
2456                         while (matrix[l][first_nonspace] == ' ')
2457                         {
2458                                 first_nonspace++;
2459                         }
2460                         first_nonspace--;
2461                         // Draw the `- (corner) section: this may be overwritten by
2462                         // another L shape passing along the same vertical pane, becoming
2463                         // a |- (branch) section instead.
2464                         matrix[l][first_nonspace] = '-';
2465                         matrix[l][first_nonspace-1] = '`';
2466                         int l2 = l - 1;
2467                         // Draw upwards until we hit the parent server, causing possibly
2468                         // other corners (`-) to become branches (|-)
2469                         while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
2470                         {
2471                                 matrix[l2][first_nonspace-1] = '|';
2472                                 l2--;
2473                         }
2474                 }
2475                 // dump the whole lot to the user. This is the easy bit, honest.
2476                 for (int t = 0; t < line; t++)
2477                 {
2478                         WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
2479                 }
2480                 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
2481                 return;
2482         }
2483
2484         int HandleSquit(char** parameters, int pcnt, userrec* user)
2485         {
2486                 TreeServer* s = FindServerMask(parameters[0]);
2487                 if (s)
2488                 {
2489                         if (s == TreeRoot)
2490                         {
2491                                  WriteServ(user->fd,"NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
2492                                 return 1;
2493                         }
2494                         TreeSocket* sock = s->GetSocket();
2495                         if (sock)
2496                         {
2497                                 log(DEBUG,"Splitting server %s",s->GetName().c_str());
2498                                 WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
2499                                 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
2500                                 sock->Close();
2501                         }
2502                         else
2503                         {
2504                                 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
2505                         }
2506                 }
2507                 else
2508                 {
2509                          WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
2510                 }
2511                 return 1;
2512         }
2513
2514         int HandleRemoteWhois(char** parameters, int pcnt, userrec* user)
2515         {
2516                 if ((user->fd > -1) && (pcnt > 1))
2517                 {
2518                         userrec* remote = Srv->FindNick(parameters[1]);
2519                         if ((remote) && (remote->fd < 0))
2520                         {
2521                                 std::deque<std::string> params;
2522                                 params.push_back(parameters[1]);
2523                                 DoOneToOne(user->nick,"IDLE",params,remote->server);
2524                                 return 1;
2525                         }
2526                         else if (!remote)
2527                         {
2528                                 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
2529                                 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
2530                                 return 1;
2531                         }
2532                 }
2533                 return 0;
2534         }
2535
2536         void DoPingChecks(time_t curtime)
2537         {
2538                 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
2539                 {
2540                         TreeServer* serv = TreeRoot->GetChild(j);
2541                         TreeSocket* sock = serv->GetSocket();
2542                         if (sock)
2543                         {
2544                                 if (curtime >= serv->NextPingTime())
2545                                 {
2546                                         if (serv->AnsweredLastPing())
2547                                         {
2548                                                 sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
2549                                                 serv->SetNextPingTime(curtime + 60);
2550                                         }
2551                                         else
2552                                         {
2553                                                 // they didnt answer, boot them
2554                                                 WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
2555                                                 sock->Squit(serv,"Ping timeout");
2556                                                 sock->Close();
2557                                                 return;
2558                                         }
2559                                 }
2560                         }
2561                 }
2562         }
2563
2564         void AutoConnectServers(time_t curtime)
2565         {
2566                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2567                 {
2568                         if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
2569                         {
2570                                 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
2571                                 x->NextConnectTime = curtime + x->AutoConnect;
2572                                 TreeServer* CheckDupe = FindServer(x->Name);
2573                                 if (!CheckDupe)
2574                                 {
2575                                         // an autoconnected server is not connected. Check if its time to connect it
2576                                         WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
2577                                         TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2578                                         Srv->AddSocket(newsocket);
2579                                 }
2580                         }
2581                 }
2582         }
2583
2584         int HandleVersion(char** parameters, int pcnt, userrec* user)
2585         {
2586                 // we've already checked if pcnt > 0, so this is safe
2587                 TreeServer* found = FindServerMask(parameters[0]);
2588                 if (found)
2589                 {
2590                         std::string Version = found->GetVersion();
2591                         WriteServ(user->fd,"351 %s :%s",user->nick,Version.c_str());
2592                 }
2593                 else
2594                 {
2595                         WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
2596                 }
2597                 return 1;
2598         }
2599         
2600         int HandleConnect(char** parameters, int pcnt, userrec* user)
2601         {
2602                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2603                 {
2604                         if (Srv->MatchText(x->Name.c_str(),parameters[0]))
2605                         {
2606                                 TreeServer* CheckDupe = FindServer(x->Name);
2607                                 if (!CheckDupe)
2608                                 {
2609                                         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);
2610                                         TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2611                                         Srv->AddSocket(newsocket);
2612                                         return 1;
2613                                 }
2614                                 else
2615                                 {
2616                                         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());
2617                                         return 1;
2618                                 }
2619                         }
2620                 }
2621                 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
2622                 return 1;
2623         }
2624
2625         virtual bool HandleStats(char ** parameters, int pcnt, userrec* user)
2626         {
2627                 if (*parameters[0] == 'c')
2628                 {
2629                         for (unsigned int i = 0; i < LinkBlocks.size(); i++)
2630                         {
2631                                 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"));
2632                                 WriteServ(user->fd,"244 %s H * * %s",user->nick,LinkBlocks[i].Name.c_str());
2633                         }
2634                         WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
2635                         WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
2636                         return true;
2637                 }
2638                 return false;
2639         }
2640
2641         virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user, bool validated)
2642         {
2643                 /* If the command doesnt appear to be valid, we dont want to mess with it. */
2644                 if (!validated)
2645                         return 0;
2646
2647                 if (command == "CONNECT")
2648                 {
2649                         return this->HandleConnect(parameters,pcnt,user);
2650                 }
2651                 else if (command == "SQUIT")
2652                 {
2653                         return this->HandleSquit(parameters,pcnt,user);
2654                 }
2655                 else if (command == "STATS")
2656                 {
2657                         return this->HandleStats(parameters,pcnt,user);
2658                 }
2659                 else if (command == "MAP")
2660                 {
2661                         this->HandleMap(parameters,pcnt,user);
2662                         return 1;
2663                 }
2664                 else if (command == "LUSERS")
2665                 {
2666                         this->HandleLusers(parameters,pcnt,user);
2667                         return 1;
2668                 }
2669                 else if (command == "LINKS")
2670                 {
2671                         this->HandleLinks(parameters,pcnt,user);
2672                         return 1;
2673                 }
2674                 else if (command == "WHOIS")
2675                 {
2676                         if (pcnt > 1)
2677                         {
2678                                 // remote whois
2679                                 return this->HandleRemoteWhois(parameters,pcnt,user);
2680                         }
2681                 }
2682                 else if ((command == "VERSION") && (pcnt > 0))
2683                 {
2684                         this->HandleVersion(parameters,pcnt,user);
2685                         return 1;
2686                 }
2687                 else if (Srv->IsValidModuleCommand(command, pcnt, user))
2688                 {
2689                         // this bit of code cleverly routes all module commands
2690                         // to all remote severs *automatically* so that modules
2691                         // can just handle commands locally, without having
2692                         // to have any special provision in place for remote
2693                         // commands and linking protocols.
2694                         std::deque<std::string> params;
2695                         params.clear();
2696                         for (int j = 0; j < pcnt; j++)
2697                         {
2698                                 if (strchr(parameters[j],' '))
2699                                 {
2700                                         params.push_back(":" + std::string(parameters[j]));
2701                                 }
2702                                 else
2703                                 {
2704                                         params.push_back(std::string(parameters[j]));
2705                                 }
2706                         }
2707                         DoOneToMany(user->nick,command,params);
2708                 }
2709                 return 0;
2710         }
2711
2712         virtual void OnGetServerDescription(std::string servername,std::string &description)
2713         {
2714                 TreeServer* s = FindServer(servername);
2715                 if (s)
2716                 {
2717                         description = s->GetDesc();
2718                 }
2719         }
2720
2721         virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
2722         {
2723                 if (source->fd > -1)
2724                 {
2725                         std::deque<std::string> params;
2726                         params.push_back(dest->nick);
2727                         params.push_back(channel->name);
2728                         DoOneToMany(source->nick,"INVITE",params);
2729                 }
2730         }
2731
2732         virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
2733         {
2734                 std::deque<std::string> params;
2735                 params.push_back(chan->name);
2736                 params.push_back(":"+topic);
2737                 DoOneToMany(user->nick,"TOPIC",params);
2738         }
2739
2740         virtual void OnWallops(userrec* user, std::string text)
2741         {
2742                 if (user->fd > -1)
2743                 {
2744                         std::deque<std::string> params;
2745                         params.push_back(":"+text);
2746                         DoOneToMany(user->nick,"WALLOPS",params);
2747                 }
2748         }
2749
2750         virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
2751         {
2752                 if (target_type == TYPE_USER)
2753                 {
2754                         userrec* d = (userrec*)dest;
2755                         if ((d->fd < 0) && (user->fd > -1))
2756                         {
2757                                 std::deque<std::string> params;
2758                                 params.clear();
2759                                 params.push_back(d->nick);
2760                                 params.push_back(":"+text);
2761                                 DoOneToOne(user->nick,"NOTICE",params,d->server);
2762                         }
2763                 }
2764                 else
2765                 {
2766                         if (user->fd > -1)
2767                         {
2768                                 chanrec *c = (chanrec*)dest;
2769                                 std::deque<TreeServer*> list;
2770                                 GetListOfServersForChannel(c,list);
2771                                 unsigned int ucount = list.size();
2772                                 for (unsigned int i = 0; i < ucount; i++)
2773                                 {
2774                                         TreeSocket* Sock = list[i]->GetSocket();
2775                                         if (Sock)
2776                                                 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+std::string(c->name)+" :"+text);
2777                                 }
2778                         }
2779                 }
2780         }
2781
2782         virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
2783         {
2784                 if (target_type == TYPE_USER)
2785                 {
2786                         // route private messages which are targetted at clients only to the server
2787                         // which needs to receive them
2788                         userrec* d = (userrec*)dest;
2789                         if ((d->fd < 0) && (user->fd > -1))
2790                         {
2791                                 std::deque<std::string> params;
2792                                 params.clear();
2793                                 params.push_back(d->nick);
2794                                 params.push_back(":"+text);
2795                                 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
2796                         }
2797                 }
2798                 else
2799                 {
2800                         if (user->fd > -1)
2801                         {
2802                                 chanrec *c = (chanrec*)dest;
2803                                 std::deque<TreeServer*> list;
2804                                 GetListOfServersForChannel(c,list);
2805                                 unsigned int ucount = list.size();
2806                                 for (unsigned int i = 0; i < ucount; i++)
2807                                 {
2808                                         TreeSocket* Sock = list[i]->GetSocket();
2809                                         if (Sock)
2810                                                 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+std::string(c->name)+" :"+text);
2811                                 }
2812                         }
2813                 }
2814         }
2815
2816         virtual void OnBackgroundTimer(time_t curtime)
2817         {
2818                 AutoConnectServers(curtime);
2819                 DoPingChecks(curtime);
2820         }
2821
2822         virtual void OnUserJoin(userrec* user, chanrec* channel)
2823         {
2824                 // Only do this for local users
2825                 if (user->fd > -1)
2826                 {
2827                         std::deque<std::string> params;
2828                         params.clear();
2829                         params.push_back(channel->name);
2830                         if (*channel->key)
2831                         {
2832                                 // if the channel has a key, force the join by emulating the key.
2833                                 params.push_back(channel->key);
2834                         }
2835                         if (channel->GetUserCounter() > 1)
2836                         {
2837                                 // not the first in the channel
2838                                 DoOneToMany(user->nick,"JOIN",params);
2839                         }
2840                         else
2841                         {
2842                                 // first in the channel, set up their permissions
2843                                 // and the channel TS with FJOIN.
2844                                 char ts[24];
2845                                 snprintf(ts,24,"%lu",(unsigned long)channel->age);
2846                                 params.clear();
2847                                 params.push_back(channel->name);
2848                                 params.push_back(ts);
2849                                 params.push_back("@"+std::string(user->nick));
2850                                 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
2851                         }
2852                 }
2853         }
2854
2855         virtual void OnChangeHost(userrec* user, std::string newhost)
2856         {
2857                 // only occurs for local clients
2858                 if (user->registered != 7)
2859                         return;
2860                 std::deque<std::string> params;
2861                 params.push_back(newhost);
2862                 DoOneToMany(user->nick,"FHOST",params);
2863         }
2864
2865         virtual void OnChangeName(userrec* user, std::string gecos)
2866         {
2867                 // only occurs for local clients
2868                 if (user->registered != 7)
2869                         return;
2870                 std::deque<std::string> params;
2871                 params.push_back(gecos);
2872                 DoOneToMany(user->nick,"FNAME",params);
2873         }
2874
2875         virtual void OnUserPart(userrec* user, chanrec* channel)
2876         {
2877                 if (user->fd > -1)
2878                 {
2879                         std::deque<std::string> params;
2880                         params.push_back(channel->name);
2881                         DoOneToMany(user->nick,"PART",params);
2882                 }
2883         }
2884
2885         virtual void OnUserConnect(userrec* user)
2886         {
2887                 char agestr[MAXBUF];
2888                 if (user->fd > -1)
2889                 {
2890                         std::deque<std::string> params;
2891                         snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
2892                         params.push_back(agestr);
2893                         params.push_back(user->nick);
2894                         params.push_back(user->host);
2895                         params.push_back(user->dhost);
2896                         params.push_back(user->ident);
2897                         params.push_back("+"+std::string(user->modes));
2898                         params.push_back(user->ip);
2899                         params.push_back(":"+std::string(user->fullname));
2900                         DoOneToMany(Srv->GetServerName(),"NICK",params);
2901                 }
2902         }
2903
2904         virtual void OnUserQuit(userrec* user, std::string reason)
2905         {
2906                 if ((user->fd > -1) && (user->registered == 7))
2907                 {
2908                         std::deque<std::string> params;
2909                         params.push_back(":"+reason);
2910                         DoOneToMany(user->nick,"QUIT",params);
2911                 }
2912         }
2913
2914         virtual void OnUserPostNick(userrec* user, std::string oldnick)
2915         {
2916                 if (user->fd > -1)
2917                 {
2918                         std::deque<std::string> params;
2919                         params.push_back(user->nick);
2920                         DoOneToMany(oldnick,"NICK",params);
2921                 }
2922         }
2923
2924         virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
2925         {
2926                 if (source->fd > -1)
2927                 {
2928                         std::deque<std::string> params;
2929                         params.push_back(chan->name);
2930                         params.push_back(user->nick);
2931                         params.push_back(":"+reason);
2932                         DoOneToMany(source->nick,"KICK",params);
2933                 }
2934         }
2935
2936         virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
2937         {
2938                 std::deque<std::string> params;
2939                 params.push_back(dest->nick);
2940                 params.push_back(":"+reason);
2941                 DoOneToMany(source->nick,"KILL",params);
2942         }
2943
2944         virtual void OnRehash(std::string parameter)
2945         {
2946                 if (parameter != "")
2947                 {
2948                         std::deque<std::string> params;
2949                         params.push_back(parameter);
2950                         DoOneToMany(Srv->GetServerName(),"REHASH",params);
2951                         // check for self
2952                         if (Srv->MatchText(Srv->GetServerName(),parameter))
2953                         {
2954                                 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
2955                                 Srv->RehashServer();
2956                         }
2957                 }
2958                 ReadConfiguration(false);
2959         }
2960
2961         // note: the protocol does not allow direct umode +o except
2962         // via NICK with 8 params. sending OPERTYPE infers +o modechange
2963         // locally.
2964         virtual void OnOper(userrec* user, std::string opertype)
2965         {
2966                 if (user->fd > -1)
2967                 {
2968                         std::deque<std::string> params;
2969                         params.push_back(opertype);
2970                         DoOneToMany(user->nick,"OPERTYPE",params);
2971                 }
2972         }
2973
2974         void OnLine(userrec* source, std::string host, bool adding, char linetype, long duration, std::string reason)
2975         {
2976                 if (source->fd > -1)
2977                 {
2978                         char type[8];
2979                         snprintf(type,8,"%cLINE",linetype);
2980                         std::string stype = type;
2981                         if (adding)
2982                         {
2983                                 char sduration[MAXBUF];
2984                                 snprintf(sduration,MAXBUF,"%ld",duration);
2985                                 std::deque<std::string> params;
2986                                 params.push_back(host);
2987                                 params.push_back(sduration);
2988                                 params.push_back(":"+reason);
2989                                 DoOneToMany(source->nick,stype,params);
2990                         }
2991                         else
2992                         {
2993                                 std::deque<std::string> params;
2994                                 params.push_back(host);
2995                                 DoOneToMany(source->nick,stype,params);
2996                         }
2997                 }
2998         }
2999
3000         virtual void OnAddGLine(long duration, userrec* source, std::string reason, std::string hostmask)
3001         {
3002                 OnLine(source,hostmask,true,'G',duration,reason);
3003         }
3004         
3005         virtual void OnAddZLine(long duration, userrec* source, std::string reason, std::string ipmask)
3006         {
3007                 OnLine(source,ipmask,true,'Z',duration,reason);
3008         }
3009
3010         virtual void OnAddQLine(long duration, userrec* source, std::string reason, std::string nickmask)
3011         {
3012                 OnLine(source,nickmask,true,'Q',duration,reason);
3013         }
3014
3015         virtual void OnAddELine(long duration, userrec* source, std::string reason, std::string hostmask)
3016         {
3017                 OnLine(source,hostmask,true,'E',duration,reason);
3018         }
3019
3020         virtual void OnDelGLine(userrec* source, std::string hostmask)
3021         {
3022                 OnLine(source,hostmask,false,'G',0,"");
3023         }
3024
3025         virtual void OnDelZLine(userrec* source, std::string ipmask)
3026         {
3027                 OnLine(source,ipmask,false,'Z',0,"");
3028         }
3029
3030         virtual void OnDelQLine(userrec* source, std::string nickmask)
3031         {
3032                 OnLine(source,nickmask,false,'Q',0,"");
3033         }
3034
3035         virtual void OnDelELine(userrec* source, std::string hostmask)
3036         {
3037                 OnLine(source,hostmask,false,'E',0,"");
3038         }
3039
3040         virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
3041         {
3042                 if ((user->fd > -1) && (user->registered == 7))
3043                 {
3044                         if (target_type == TYPE_USER)
3045                         {
3046                                 userrec* u = (userrec*)dest;
3047                                 std::deque<std::string> params;
3048                                 params.push_back(u->nick);
3049                                 params.push_back(text);
3050                                 DoOneToMany(user->nick,"MODE",params);
3051                         }
3052                         else
3053                         {
3054                                 chanrec* c = (chanrec*)dest;
3055                                 std::deque<std::string> params;
3056                                 params.push_back(c->name);
3057                                 params.push_back(text);
3058                                 DoOneToMany(user->nick,"MODE",params);
3059                         }
3060                 }
3061         }
3062
3063         virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
3064         {
3065                 TreeSocket* s = (TreeSocket*)opaque;
3066                 if (target)
3067                 {
3068                         if (target_type == TYPE_USER)
3069                         {
3070                                 userrec* u = (userrec*)target;
3071                                 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
3072                         }
3073                         else
3074                         {
3075                                 chanrec* c = (chanrec*)target;
3076                                 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
3077                         }
3078                 }
3079         }
3080
3081         virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, std::string extname, std::string extdata)
3082         {
3083                 TreeSocket* s = (TreeSocket*)opaque;
3084                 if (target)
3085                 {
3086                         if (target_type == TYPE_USER)
3087                         {
3088                                 userrec* u = (userrec*)target;
3089                                 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+u->nick+" "+extname+" :"+extdata);
3090                         }
3091                         else
3092                         {
3093                                 chanrec* c = (chanrec*)target;
3094                                 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+c->name+" "+extname+" :"+extdata);
3095                         }
3096                 }
3097         }
3098
3099         virtual ~ModuleSpanningTree()
3100         {
3101         }
3102
3103         virtual Version GetVersion()
3104         {
3105                 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
3106         }
3107 };
3108
3109
3110 class ModuleSpanningTreeFactory : public ModuleFactory
3111 {
3112  public:
3113         ModuleSpanningTreeFactory()
3114         {
3115         }
3116         
3117         ~ModuleSpanningTreeFactory()
3118         {
3119         }
3120         
3121         virtual Module * CreateModule(Server* Me)
3122         {
3123                 TreeProtocolModule = new ModuleSpanningTree(Me);
3124                 return TreeProtocolModule;
3125         }
3126         
3127 };
3128
3129
3130 extern "C" void * init_module( void )
3131 {
3132         return new ModuleSpanningTreeFactory;
3133 }