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