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