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