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