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