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