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