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