]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree.cpp
d4bc5360ec4db8851ea3b9693c8d4415aac56a1a
[user/henk/code/inspircd.git] / src / modules / m_spanningtree.cpp
1 /*   +------------------------------------+
2  *   | Inspire Internet Relay Chat Daemon |
3  *   +------------------------------------+
4  *
5  *  InspIRCd is copyright (C) 2002-2006 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 #include "hash_map.h"
27 #include "configreader.h"
28 #include "users.h"
29 #include "channels.h"
30 #include "modules.h"
31 #include "commands.h"
32 #include "commands/cmd_whois.h"
33 #include "commands/cmd_stats.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 #include "typedefs.h"
42 #include "cull_list.h"
43 #include "aes.h"
44
45 #define nspace __gnu_cxx
46
47 /*
48  * The server list in InspIRCd is maintained as two structures
49  * which hold the data in different ways. Most of the time, we
50  * want to very quicky obtain three pieces of information:
51  *
52  * (1) The information on a server
53  * (2) The information on the server we must send data through
54  *     to actually REACH the server we're after
55  * (3) Potentially, the child/parent objects of this server
56  *
57  * The InspIRCd spanning protocol provides easy access to these
58  * by storing the data firstly in a recursive structure, where
59  * each item references its parent item, and a dynamic list
60  * of child items, and another structure which stores the items
61  * hashed, linearly. This means that if we want to find a server
62  * by name quickly, we can look it up in the hash, avoiding
63  * any O(n) lookups. If however, during a split or sync, we want
64  * to apply an operation to a server, and any of its child objects
65  * we can resort to recursion to walk the tree structure.
66  */
67
68 class ModuleSpanningTree;
69 static ModuleSpanningTree* TreeProtocolModule;
70
71 extern ServerConfig* Config;
72 extern InspIRCd* ServerInstance;
73 extern std::vector<Module*> modules;
74 extern std::vector<ircd_module*> factory;
75 extern int MODCOUNT;
76
77 /* Any socket can have one of five states at any one time.
78  * The LISTENER state indicates a socket which is listening
79  * for connections. It cannot receive data itself, only incoming
80  * sockets.
81  * The CONNECTING state indicates an outbound socket which is
82  * waiting to be writeable.
83  * The WAIT_AUTH_1 state indicates the socket is outbound and
84  * has successfully connected, but has not yet sent and received
85  * SERVER strings.
86  * The WAIT_AUTH_2 state indicates that the socket is inbound
87  * (allocated by a LISTENER) but has not yet sent and received
88  * SERVER strings.
89  * The CONNECTED state represents a fully authorized, fully
90  * connected server.
91  */
92 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
93
94 /* We need to import these from the core for use in netbursts */
95 extern user_hash clientlist;
96 extern chan_hash chanlist;
97
98 /* Foward declarations */
99 class TreeServer;
100 class TreeSocket;
101
102 /* This variable represents the root of the server tree
103  * (for all intents and purposes, it's us)
104  */
105 TreeServer *TreeRoot;
106
107 static Server* Srv;
108
109 /* This hash_map holds the hash equivalent of the server
110  * tree, used for rapid linear lookups.
111  */
112 typedef nspace::hash_map<std::string, TreeServer*, nspace::hash<string>, irc::StrHashComp> server_hash;
113 server_hash serverlist;
114
115 typedef nspace::hash_map<std::string, userrec*> uid_hash;
116 typedef nspace::hash_map<std::string, char*> sid_hash;
117
118 /* More forward declarations */
119 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> &params, std::string target);
120 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> &params, std::string omit);
121 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> &params);
122 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, irc::string command, std::deque<std::string> &params);
123 void ReadConfiguration(bool rebind);
124
125 /* Flatten links and /MAP for non-opers */
126 bool FlatLinks;
127 /* Hide U-Lined servers in /MAP and /LINKS */
128 bool HideULines;
129
130 /* Imported from xline.cpp for use during netburst */
131 extern std::vector<KLine> klines;
132 extern std::vector<GLine> glines;
133 extern std::vector<ZLine> zlines;
134 extern std::vector<QLine> qlines;
135 extern std::vector<ELine> elines;
136 extern std::vector<KLine> pklines;
137 extern std::vector<GLine> pglines;
138 extern std::vector<ZLine> pzlines;
139 extern std::vector<QLine> pqlines;
140 extern std::vector<ELine> pelines;
141
142 class UserManager : public classbase
143 {
144         uid_hash uids;
145         sid_hash sids;
146  public:
147         UserManager()
148         {
149                 uids.clear();
150                 sids.clear();
151         }
152
153         std::string UserToUID(userrec* user)
154         {
155                 return "";
156         }
157
158         std::string UIDToUser(const std::string &UID)
159         {
160                 return "";
161         }
162
163         std::string CreateAndAdd(userrec* user)
164         {
165                 return "";
166         }
167
168         std::string CreateAndAdd(const std::string &servername)
169         {
170                 return "";
171         }
172
173         std::string ServerToSID(const std::string &servername)
174         {
175                 return "";
176         }
177
178         std::string SIDToServer(const std::string &SID)
179         {
180                 return "";
181         }
182
183         userrec* FindByID(const std::string &UID)
184         {
185                 return NULL;
186         }
187 };
188
189
190 /* Each server in the tree is represented by one class of
191  * type TreeServer. A locally connected TreeServer can
192  * have a class of type TreeSocket associated with it, for
193  * remote servers, the TreeSocket entry will be NULL.
194  * Each server also maintains a pointer to its parent
195  * (NULL if this server is ours, at the top of the tree)
196  * and a pointer to its "Route" (see the comments in the
197  * constructors below), and also a dynamic list of pointers
198  * to its children which can be iterated recursively
199  * if required. Creating or deleting objects of type
200  i* TreeServer automatically maintains the hash_map of
201  * TreeServer items, deleting and inserting them as they
202  * are created and destroyed.
203  */
204
205 class TreeServer : public classbase
206 {
207         TreeServer* Parent;                     /* Parent entry */
208         TreeServer* Route;                      /* Route entry */
209         std::vector<TreeServer*> Children;      /* List of child objects */
210         irc::string ServerName;                 /* Server's name */
211         std::string ServerDesc;                 /* Server's description */
212         std::string VersionString;              /* Version string or empty string */
213         int UserCount;                          /* Not used in this version */
214         int OperCount;                          /* Not used in this version */
215         TreeSocket* Socket;                     /* For directly connected servers this points at the socket object */
216         time_t NextPing;                        /* After this time, the server should be PINGed*/
217         bool LastPingWasGood;                   /* True if the server responded to the last PING with a PONG */
218         
219  public:
220
221         /* We don't use this constructor. Its a dummy, and won't cause any insertion
222          * of the TreeServer into the hash_map. See below for the two we DO use.
223          */
224         TreeServer()
225         {
226                 Parent = NULL;
227                 ServerName = "";
228                 ServerDesc = "";
229                 VersionString = "";
230                 UserCount = OperCount = 0;
231                 VersionString = Srv->GetVersion();
232         }
233
234         /* We use this constructor only to create the 'root' item, TreeRoot, which
235          * represents our own server. Therefore, it has no route, no parent, and
236          * no socket associated with it. Its version string is our own local version.
237          */
238         TreeServer(std::string Name, std::string Desc) : ServerName(Name.c_str()), ServerDesc(Desc)
239         {
240                 Parent = NULL;
241                 VersionString = "";
242                 UserCount = OperCount = 0;
243                 VersionString = Srv->GetVersion();
244                 Route = NULL;
245                 Socket = NULL; /* Fix by brain */
246                 AddHashEntry();
247         }
248
249         /* When we create a new server, we call this constructor to initialize it.
250          * This constructor initializes the server's Route and Parent, and sets up
251          * its ping counters so that it will be pinged one minute from now.
252          */
253         TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name.c_str()), ServerDesc(Desc), Socket(Sock)
254         {
255                 VersionString = "";
256                 UserCount = OperCount = 0;
257                 this->SetNextPingTime(time(NULL) + 120);
258                 this->SetPingFlag();
259
260                 /* find the 'route' for this server (e.g. the one directly connected
261                  * to the local server, which we can use to reach it)
262                  *
263                  * In the following example, consider we have just added a TreeServer
264                  * class for server G on our network, of which we are server A.
265                  * To route traffic to G (marked with a *) we must send the data to
266                  * B (marked with a +) so this algorithm initializes the 'Route'
267                  * value to point at whichever server traffic must be routed through
268                  * to get here. If we were to try this algorithm with server B,
269                  * the Route pointer would point at its own object ('this').
270                  *
271                  *              A
272                  *             / \
273                  *          + B   C
274                  *           / \   \
275                  *          D   E   F
276                  *         /         \
277                  *      * G           H
278                  *
279                  * We only run this algorithm when a server is created, as
280                  * the routes remain constant while ever the server exists, and
281                  * do not need to be re-calculated.
282                  */
283
284                 Route = Above;
285                 if (Route == TreeRoot)
286                 {
287                         Route = this;
288                 }
289                 else
290                 {
291                         while (this->Route->GetParent() != TreeRoot)
292                         {
293                                 this->Route = Route->GetParent();
294                         }
295                 }
296
297                 /* Because recursive code is slow and takes a lot of resources,
298                  * we store two representations of the server tree. The first
299                  * is a recursive structure where each server references its
300                  * children and its parent, which is used for netbursts and
301                  * netsplits to dump the whole dataset to the other server,
302                  * and the second is used for very fast lookups when routing
303                  * messages and is instead a hash_map, where each item can
304                  * be referenced by its server name. The AddHashEntry()
305                  * call below automatically inserts each TreeServer class
306                  * into the hash_map as it is created. There is a similar
307                  * maintainance call in the destructor to tidy up deleted
308                  * servers.
309                  */
310
311                 this->AddHashEntry();
312         }
313
314         int QuitUsers(const std::string &reason)
315         {
316                 log(DEBUG,"Removing all users from server %s",this->ServerName.c_str());
317                 const char* reason_s = reason.c_str();
318                 std::vector<userrec*> time_to_die;
319                 for (user_hash::iterator n = clientlist.begin(); n != clientlist.end(); n++)
320                 {
321                         if (!strcmp(n->second->server, this->ServerName.c_str()))
322                         {
323                                 time_to_die.push_back(n->second);
324                         }
325                 }
326                 for (std::vector<userrec*>::iterator n = time_to_die.begin(); n != time_to_die.end(); n++)
327                 {
328                         userrec* a = (userrec*)*n;
329                         log(DEBUG,"Kill %s fd=%d",a->nick,a->fd);
330                         if (!IS_LOCAL(a))
331                                 kill_link(a,reason_s);
332                 }
333                 return time_to_die.size();
334         }
335
336         /* This method is used to add the structure to the
337          * hash_map for linear searches. It is only called
338          * by the constructors.
339          */
340         void AddHashEntry()
341         {
342                 server_hash::iterator iter;
343                 iter = serverlist.find(this->ServerName.c_str());
344                 if (iter == serverlist.end())
345                         serverlist[this->ServerName.c_str()] = this;
346         }
347
348         /* This method removes the reference to this object
349          * from the hash_map which is used for linear searches.
350          * It is only called by the default destructor.
351          */
352         void DelHashEntry()
353         {
354                 server_hash::iterator iter;
355                 iter = serverlist.find(this->ServerName.c_str());
356                 if (iter != serverlist.end())
357                         serverlist.erase(iter);
358         }
359
360         /* These accessors etc should be pretty self-
361          * explanitory.
362          */
363
364         TreeServer* GetRoute()
365         {
366                 return Route;
367         }
368
369         std::string GetName()
370         {
371                 return ServerName.c_str();
372         }
373
374         std::string GetDesc()
375         {
376                 return ServerDesc;
377         }
378
379         std::string GetVersion()
380         {
381                 return VersionString;
382         }
383
384         void SetNextPingTime(time_t t)
385         {
386                 this->NextPing = t;
387                 LastPingWasGood = false;
388         }
389
390         time_t NextPingTime()
391         {
392                 return NextPing;
393         }
394
395         bool AnsweredLastPing()
396         {
397                 return LastPingWasGood;
398         }
399
400         void SetPingFlag()
401         {
402                 LastPingWasGood = true;
403         }
404
405         int GetUserCount()
406         {
407                 return UserCount;
408         }
409
410         void AddUserCount()
411         {
412                 UserCount++;
413         }
414
415         void DelUserCount()
416         {
417                 UserCount--;
418         }
419
420         int GetOperCount()
421         {
422                 return OperCount;
423         }
424
425         TreeSocket* GetSocket()
426         {
427                 return Socket;
428         }
429
430         TreeServer* GetParent()
431         {
432                 return Parent;
433         }
434
435         void SetVersion(std::string Version)
436         {
437                 VersionString = Version;
438         }
439
440         unsigned int ChildCount()
441         {
442                 return Children.size();
443         }
444
445         TreeServer* GetChild(unsigned int n)
446         {
447                 if (n < Children.size())
448                 {
449                         /* Make sure they  cant request
450                          * an out-of-range object. After
451                          * all we know what these programmer
452                          * types are like *grin*.
453                          */
454                         return Children[n];
455                 }
456                 else
457                 {
458                         return NULL;
459                 }
460         }
461
462         void AddChild(TreeServer* Child)
463         {
464                 Children.push_back(Child);
465         }
466
467         bool DelChild(TreeServer* Child)
468         {
469                 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
470                 {
471                         if (*a == Child)
472                         {
473                                 Children.erase(a);
474                                 return true;
475                         }
476                 }
477                 return false;
478         }
479
480         /* Removes child nodes of this node, and of that node, etc etc.
481          * This is used during netsplits to automatically tidy up the
482          * server tree. It is slow, we don't use it for much else.
483          */
484         bool Tidy()
485         {
486                 bool stillchildren = true;
487                 while (stillchildren)
488                 {
489                         stillchildren = false;
490                         for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
491                         {
492                                 TreeServer* s = (TreeServer*)*a;
493                                 s->Tidy();
494                                 Children.erase(a);
495                                 DELETE(s);
496                                 stillchildren = true;
497                                 break;
498                         }
499                 }
500                 return true;
501         }
502
503         ~TreeServer()
504         {
505                 /* We'd better tidy up after ourselves, eh? */
506                 this->DelHashEntry();
507         }
508 };
509
510 /* The Link class might as well be a struct,
511  * but this is C++ and we don't believe in structs (!).
512  * It holds the entire information of one <link>
513  * tag from the main config file. We maintain a list
514  * of them, and populate the list on rehash/load.
515  */
516
517 class Link : public classbase
518 {
519  public:
520          irc::string Name;
521          std::string IPAddr;
522          int Port;
523          std::string SendPass;
524          std::string RecvPass;
525          unsigned long AutoConnect;
526          time_t NextConnectTime;
527          std::string EncryptionKey;
528          bool HiddenFromStats;
529 };
530
531 /* The usual stuff for inspircd modules,
532  * plus the vector of Link classes which we
533  * use to store the <link> tags from the config
534  * file.
535  */
536 ConfigReader *Conf;
537 std::vector<Link> LinkBlocks;
538
539 /* Yay for fast searches!
540  * This is hundreds of times faster than recursion
541  * or even scanning a linked list, especially when
542  * there are more than a few servers to deal with.
543  * (read as: lots).
544  */
545 TreeServer* FindServer(std::string ServerName)
546 {
547         server_hash::iterator iter;
548         iter = serverlist.find(ServerName.c_str());
549         if (iter != serverlist.end())
550         {
551                 return iter->second;
552         }
553         else
554         {
555                 return NULL;
556         }
557 }
558
559 /* Returns the locally connected server we must route a
560  * message through to reach server 'ServerName'. This
561  * only applies to one-to-one and not one-to-many routing.
562  * See the comments for the constructor of TreeServer
563  * for more details.
564  */
565 TreeServer* BestRouteTo(std::string ServerName)
566 {
567         if (ServerName.c_str() == TreeRoot->GetName())
568                 return NULL;
569         TreeServer* Found = FindServer(ServerName);
570         if (Found)
571         {
572                 return Found->GetRoute();
573         }
574         else
575         {
576                 return NULL;
577         }
578 }
579
580 /* Find the first server matching a given glob mask.
581  * Theres no find-using-glob method of hash_map [awwww :-(]
582  * so instead, we iterate over the list using an iterator
583  * and match each one until we get a hit. Yes its slow,
584  * deal with it.
585  */
586 TreeServer* FindServerMask(std::string ServerName)
587 {
588         for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
589         {
590                 if (Srv->MatchText(i->first.c_str(),ServerName))
591                         return i->second;
592         }
593         return NULL;
594 }
595
596 /* A convenient wrapper that returns true if a server exists */
597 bool IsServer(std::string ServerName)
598 {
599         return (FindServer(ServerName) != NULL);
600 }
601
602
603 class cmd_rconnect : public command_t
604 {
605         Module* Creator;
606  public:
607         cmd_rconnect (Module* Callback) : command_t("RCONNECT", 'o', 2), Creator(Callback)
608         {
609                 this->source = "m_spanningtree.so";
610                 syntax = "<remote-server-mask> <servermask>";
611         }
612
613         void Handle (const char** parameters, int pcnt, userrec *user)
614         {
615                 WriteServ(user->fd,"NOTICE %s :*** RCONNECT: Sending remote connect to \002%s\002 to connect server \002%s\002.",user->nick,parameters[0],parameters[1]);
616                 /* Is this aimed at our server? */
617                 if (Srv->MatchText(Srv->GetServerName(),parameters[0]))
618                 {
619                         /* Yes, initiate the given connect */
620                         WriteOpers("*** Remote CONNECT from %s matching \002%s\002, connecting server \002%s\002",user->nick,parameters[0],parameters[1]);
621                         const char* para[1];
622                         para[0] = parameters[1];
623                         Creator->OnPreCommand("CONNECT", para, 1, user, true);
624                 }
625         }
626 };
627  
628
629
630 /* Every SERVER connection inbound or outbound is represented by
631  * an object of type TreeSocket.
632  * TreeSockets, being inherited from InspSocket, can be tied into
633  * the core socket engine, and we cn therefore receive activity events
634  * for them, just like activex objects on speed. (yes really, that
635  * is a technical term!) Each of these which relates to a locally
636  * connected server is assocated with it, by hooking it onto a
637  * TreeSocket class using its constructor. In this way, we can
638  * maintain a list of servers, some of which are directly connected,
639  * some of which are not.
640  */
641
642 class TreeSocket : public InspSocket
643 {
644         std::string myhost;
645         std::string in_buffer;
646         ServerState LinkState;
647         std::string InboundServerName;
648         std::string InboundDescription;
649         int num_lost_users;
650         int num_lost_servers;
651         time_t NextPing;
652         bool LastPingWasGood;
653         bool bursting;
654         AES* ctx_in;
655         AES* ctx_out;
656         unsigned int keylength;
657         
658  public:
659
660         /* Because most of the I/O gubbins are encapsulated within
661          * InspSocket, we just call the superclass constructor for
662          * most of the action, and append a few of our own values
663          * to it.
664          */
665         TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
666                 : InspSocket(host, port, listening, maxtime)
667         {
668                 myhost = host;
669                 this->LinkState = LISTENER;
670                 this->ctx_in = NULL;
671                 this->ctx_out = NULL;
672         }
673
674         TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
675                 : InspSocket(host, port, listening, maxtime)
676         {
677                 myhost = ServerName;
678                 this->LinkState = CONNECTING;
679                 this->ctx_in = NULL;
680                 this->ctx_out = NULL;
681         }
682
683         /* When a listening socket gives us a new file descriptor,
684          * we must associate it with a socket without creating a new
685          * connection. This constructor is used for this purpose.
686          */
687         TreeSocket(int newfd, char* ip)
688                 : InspSocket(newfd, ip)
689         {
690                 this->LinkState = WAIT_AUTH_1;
691                 this->ctx_in = NULL;
692                 this->ctx_out = NULL;
693                 this->SendCapabilities();
694         }
695
696         ~TreeSocket()
697         {
698                 if (ctx_in)
699                         DELETE(ctx_in);
700                 if (ctx_out)
701                         DELETE(ctx_out);
702         }
703
704         void InitAES(std::string key,std::string SName)
705         {
706                 if (key == "")
707                         return;
708
709                 ctx_in = new AES();
710                 ctx_out = new AES();
711                 log(DEBUG,"Initialized AES key %s",key.c_str());
712                 // key must be 16, 24, 32 etc bytes (multiple of 8)
713                 keylength = key.length();
714                 if (!(keylength == 16 || keylength == 24 || keylength == 32))
715                 {
716                         WriteOpers("*** \2ERROR\2: Key length for encryptionkey is not 16, 24 or 32 bytes in length!");
717                         log(DEBUG,"Key length not 16, 24 or 32 characters!");
718                 }
719                 else
720                 {
721                         WriteOpers("*** \2AES\2: Initialized %d bit encryption to server %s",keylength*8,SName.c_str());
722                         ctx_in->MakeKey(key.c_str(), "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\
723                                 \0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", keylength, keylength);
724                         ctx_out->MakeKey(key.c_str(), "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\
725                                 \0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", keylength, keylength);
726                 }
727         }
728         
729         /* When an outbound connection finishes connecting, we receive
730          * this event, and must send our SERVER string to the other
731          * side. If the other side is happy, as outlined in the server
732          * to server docs on the inspircd.org site, the other side
733          * will then send back its own server string.
734          */
735         virtual bool OnConnected()
736         {
737                 if (this->LinkState == CONNECTING)
738                 {
739                         /* we do not need to change state here. */
740                         for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
741                         {
742                                 if (x->Name == this->myhost)
743                                 {
744                                         Srv->SendOpers("*** Connection to \2"+myhost+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] established.");
745                                         this->SendCapabilities();
746                                         if (x->EncryptionKey != "")
747                                         {
748                                                 if (!(x->EncryptionKey.length() == 16 || x->EncryptionKey.length() == 24 || x->EncryptionKey.length() == 32))
749                                                 {
750                                                         WriteOpers("\2WARNING\2: Your encryption key is NOT 16, 24 or 32 characters in length, encryption will \2NOT\2 be enabled.");
751                                                 }
752                                                 else
753                                                 {
754                                                         this->WriteLine("AES "+Srv->GetServerName());
755                                                         this->InitAES(x->EncryptionKey,x->Name.c_str());
756                                                 }
757                                         }
758                                         /* found who we're supposed to be connecting to, send the neccessary gubbins. */
759                                         this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
760                                         return true;
761                                 }
762                         }
763                 }
764                 /* There is a (remote) chance that between the /CONNECT and the connection
765                  * being accepted, some muppet has removed the <link> block and rehashed.
766                  * If that happens the connection hangs here until it's closed. Unlikely
767                  * and rather harmless.
768                  */
769                 Srv->SendOpers("*** Connection to \2"+myhost+"\2 lost link tag(!)");
770                 return true;
771         }
772         
773         virtual void OnError(InspSocketError e)
774         {
775                 /* We don't handle this method, because all our
776                  * dirty work is done in OnClose() (see below)
777                  * which is still called on error conditions too.
778                  */
779                 if (e == I_ERR_CONNECT)
780                 {
781                         Srv->SendOpers("*** Connection failed: Connection refused");
782                 }
783         }
784
785         virtual int OnDisconnect()
786         {
787                 /* For the same reason as above, we don't
788                  * handle OnDisconnect()
789                  */
790                 return true;
791         }
792
793         /* Recursively send the server tree with distances as hops.
794          * This is used during network burst to inform the other server
795          * (and any of ITS servers too) of what servers we know about.
796          * If at any point any of these servers already exist on the other
797          * end, our connection may be terminated. The hopcounts given
798          * by this function are relative, this doesn't matter so long as
799          * they are all >1, as all the remote servers re-calculate them
800          * to be relative too, with themselves as hop 0.
801          */
802         void SendServers(TreeServer* Current, TreeServer* s, int hops)
803         {
804                 char command[1024];
805                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
806                 {
807                         TreeServer* recursive_server = Current->GetChild(q);
808                         if (recursive_server != s)
809                         {
810                                 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
811                                 this->WriteLine(command);
812                                 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
813                                 /* down to next level */
814                                 this->SendServers(recursive_server, s, hops+1);
815                         }
816                 }
817         }
818
819         std::string MyCapabilities()
820         {
821                 ServerConfig* Config = Srv->GetConfig();
822                 std::vector<std::string> modlist;
823                 std::string capabilities = "";
824
825                 for (int i = 0; i <= MODCOUNT; i++)
826                 {
827                         if ((modules[i]->GetVersion().Flags & VF_STATIC) || (modules[i]->GetVersion().Flags & VF_COMMON))
828                                 modlist.push_back(Config->module_names[i]);
829                 }
830                 sort(modlist.begin(),modlist.end());
831                 for (unsigned int i = 0; i < modlist.size(); i++)
832                 {
833                         if (i)
834                                 capabilities = capabilities + ",";
835                         capabilities = capabilities + modlist[i];
836                 }
837                 return capabilities;
838         }
839         
840         void SendCapabilities()
841         {
842                 this->WriteLine("CAPAB "+MyCapabilities());
843         }
844
845         bool Capab(std::deque<std::string> params)
846         {
847                 if (params.size() != 1)
848                 {
849                         this->WriteLine("ERROR :Invalid number of parameters for CAPAB");
850                         return false;
851                 }
852
853                 if (params[0] != this->MyCapabilities())
854                 {
855                         std::string quitserver = this->myhost;
856                         if (this->InboundServerName != "")
857                         {
858                                 quitserver = this->InboundServerName;
859                         }
860
861                         WriteOpers("*** \2ERROR\2: Server '%s' does not have the same set of modules loaded, cannot link!",quitserver.c_str());
862                         WriteOpers("*** Our networked module set is: '%s'",this->MyCapabilities().c_str());
863                         WriteOpers("*** Other server's networked module set is: '%s'",params[0].c_str());
864                         WriteOpers("*** These lists must match exactly on both servers. Please correct these errors, and try again.");
865                         this->WriteLine("ERROR :CAPAB mismatch; My capabilities: '"+this->MyCapabilities()+"'");
866                         return false;
867                 }
868
869                 return true;
870         }
871
872         /* This function forces this server to quit, removing this server
873          * and any users on it (and servers and users below that, etc etc).
874          * It's very slow and pretty clunky, but luckily unless your network
875          * is having a REAL bad hair day, this function shouldnt be called
876          * too many times a month ;-)
877          */
878         void SquitServer(std::string &from, TreeServer* Current)
879         {
880                 /* recursively squit the servers attached to 'Current'.
881                  * We're going backwards so we don't remove users
882                  * while we still need them ;)
883                  */
884                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
885                 {
886                         TreeServer* recursive_server = Current->GetChild(q);
887                         this->SquitServer(from,recursive_server);
888                 }
889                 /* Now we've whacked the kids, whack self */
890                 num_lost_servers++;
891                 num_lost_users += Current->QuitUsers(from);
892         }
893
894         /* This is a wrapper function for SquitServer above, which
895          * does some validation first and passes on the SQUIT to all
896          * other remaining servers.
897          */
898         void Squit(TreeServer* Current,std::string reason)
899         {
900                 if ((Current) && (Current != TreeRoot))
901                 {
902                         std::deque<std::string> params;
903                         params.push_back(Current->GetName());
904                         params.push_back(":"+reason);
905                         DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
906                         if (Current->GetParent() == TreeRoot)
907                         {
908                                 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
909                         }
910                         else
911                         {
912                                 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
913                         }
914                         num_lost_servers = 0;
915                         num_lost_users = 0;
916                         std::string from = Current->GetParent()->GetName()+" "+Current->GetName();
917                         SquitServer(from, Current);
918                         Current->Tidy();
919                         Current->GetParent()->DelChild(Current);
920                         DELETE(Current);
921                         WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
922                 }
923                 else
924                 {
925                         log(DEFAULT,"Squit from unknown server");
926                 }
927         }
928
929         /* FMODE command - server mode with timestamp checks */
930         bool ForceMode(std::string source, std::deque<std::string> &params)
931         {
932                 /* Chances are this is a 1.0 FMODE without TS */
933                 if (params.size() < 3)
934                 {
935                         this->WriteLine("ERROR :Version 1.0 FMODE sent to version 1.1 server");
936                         return false;
937                 }
938                 
939                 bool smode = false;
940                 std::string sourceserv;
941
942                 /* Are we dealing with an FMODE from a user, or from a server? */
943                 userrec* who = Srv->FindNick(source);
944                 if (who)
945                 {
946                         /* FMODE from a user, set sourceserv to the users server name */
947                         sourceserv = who->server;
948                 }
949                 else
950                 {
951                         /* FMODE from a server, create a fake user to receive mode feedback */
952                         who = new userrec();
953                         who->fd = FD_MAGIC_NUMBER;
954                         smode = true;           /* Setting this flag tells us we should free the userrec later */
955                         sourceserv = source;    /* Set sourceserv to the actual source string */
956                 }
957                 const char* modelist[64];
958                 time_t TS = 0;
959                 int n = 0;
960                 memset(&modelist,0,sizeof(modelist));
961                 for (unsigned int q = 0; (q < params.size()) && (q < 64); q++)
962                 {
963                         if (q == 1)
964                         {
965                                 /* The timestamp is in this position.
966                                  * We don't want to pass that up to the
967                                  * server->client protocol!
968                                  */
969                                 TS = atoi(params[q].c_str());
970                         }
971                         else
972                         {
973                                 /* Everything else is fine to append to the modelist */
974                                 modelist[n++] = params[q].c_str();
975                         }
976                                 
977                 }
978                 /* Extract the TS value of the object, either userrec or chanrec */
979                 userrec* dst = Srv->FindNick(params[0]);
980                 chanrec* chan = NULL;
981                 time_t ourTS = 0;
982                 if (dst)
983                 {
984                         ourTS = dst->age;
985                 }
986                 else
987                 {
988                         chan = Srv->FindChannel(params[0]);
989                         if (chan)
990                         {
991                                 ourTS = chan->age;
992                         }
993                 }
994
995                 /* TS is equal: Merge the mode changes, use voooodoooooo on modes
996                  * with parameters.
997                  */
998                 if (TS == ourTS)
999                 {
1000                         log(DEBUG,"Entering TS equality check");
1001                         ModeHandler* mh = NULL;
1002                         unsigned long paramptr = 3;
1003                         std::string to_bounce = "";
1004                         std::string to_keep = "";
1005                         std::vector<std::string> params_to_keep;
1006                         std::string params_to_bounce = "";
1007                         bool adding = true;
1008                         char cur_change = 1;
1009                         char old_change = 0;
1010                         char old_bounce_change = 0;
1011                         /* Merge modes, basically do special stuff to mode with params */
1012                         for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
1013                         {
1014                                 switch (*x)
1015                                 {
1016                                         case '-':
1017                                                 adding = false;
1018                                         break;
1019                                         case '+':
1020                                                 adding = true;
1021                                         break;
1022                                         default:
1023                                                 if (adding)
1024                                                 {
1025                                                         /* We only care about whats being set,
1026                                                          * not whats being unset
1027                                                          */
1028                                                         mh = ServerInstance->ModeGrok->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1029
1030                                                         if ((mh->GetNumParams(adding) > 0) && (!mh->IsListMode()))
1031                                                         {
1032                                                                 /* We only want to do special things to
1033                                                                  * modes with parameters, we are going to rewrite
1034                                                                  * those parameters
1035                                                                  */
1036                                                                 ModePair ret;
1037                                                                 adding ? cur_change = '+' : cur_change = '-';
1038
1039                                                                 ret = mh->ModeSet(smode ? NULL : who, dst, chan, params[paramptr]);
1040
1041                                                                 /* The mode is set here, check which we should keep */
1042                                                                 if (ret.first)
1043                                                                 {
1044                                                                         bool which_to_keep = mh->CheckTimeStamp(TS, ourTS, params[paramptr], ret.second, chan);
1045
1046                                                                         if (which_to_keep == true)
1047                                                                         {
1048                                                                                 /* Keep ours, bounce theirs:
1049                                                                                  * Send back ours to them and
1050                                                                                  * drop their mode changs
1051                                                                                  */
1052                                                                                 adding ? cur_change = '+' : cur_change = '-';
1053                                                                                 if (cur_change != old_bounce_change)
1054                                                                                         to_bounce += cur_change;
1055                                                                                 to_bounce += *x;
1056                                                                                 old_bounce_change = cur_change;
1057
1058                                                                                 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1059                                                                                         params_to_bounce.append(" ").append(ret.second);
1060                                                                         }
1061                                                                         else
1062                                                                         {
1063                                                                                 /* Keep theirs: Accept their mode change,
1064                                                                                  * do nothing else
1065                                                                                  */
1066                                                                                 adding ? cur_change = '+' : cur_change = '-';
1067                                                                                 if (cur_change != old_change)
1068                                                                                         to_keep += cur_change;
1069                                                                                 to_keep += *x;
1070                                                                                 old_change = cur_change;
1071
1072                                                                                 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1073                                                                                         params_to_keep.push_back(params[paramptr]);
1074                                                                         }
1075                                                                 }
1076                                                                 else
1077                                                                 {
1078                                                                         /* Mode isnt set here, we want it */
1079                                                                         adding ? cur_change = '+' : cur_change = '-';
1080                                                                         if (cur_change != old_change)
1081                                                                                 to_keep += cur_change;
1082                                                                         to_keep += *x;
1083                                                                         old_change = cur_change;
1084
1085                                                                         if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1086                                                                                 params_to_keep.push_back(params[paramptr]);
1087                                                                 }
1088
1089                                                                 paramptr++;
1090                                                         }
1091                                                         else
1092                                                         {
1093                                                                 mh = ServerInstance->ModeGrok->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1094
1095                                                                 if (mh)
1096                                                                 {
1097                                                                         adding ? cur_change = '+' : cur_change = '-';
1098         
1099                                                                         /* Just keep this, safe to merge with no checks
1100                                                                          * it has no parameters
1101                                                                          */
1102         
1103                                                                         if (cur_change != old_change)
1104                                                                                 to_keep += cur_change;
1105                                                                         to_keep += *x;
1106                                                                         old_change = cur_change;
1107         
1108                                                                         if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1109                                                                         {
1110                                                                                 log(DEBUG,"Mode removal %d %d",adding, mh->GetNumParams(adding));
1111                                                                                 params_to_keep.push_back(params[paramptr++]);
1112                                                                         }
1113                                                                 }
1114                                                         }
1115                                                 }
1116                                                 else
1117                                                 {
1118                                                         mh = ServerInstance->ModeGrok->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1119
1120                                                         if (mh)
1121                                                         {
1122                                                                 /* Taking a mode away */
1123                                                                 adding ? cur_change = '+' : cur_change = '-';
1124
1125                                                                 if (cur_change != old_change)
1126                                                                         to_keep += cur_change;
1127                                                                 to_keep += *x;
1128                                                                 old_change = cur_change;
1129
1130                                                                 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1131                                                                         params_to_keep.push_back(params[paramptr++]);
1132                                                         }
1133                                                 }
1134                                         break;
1135                                 }
1136                         }
1137
1138                         if (to_bounce.length())
1139                         {
1140                                 std::deque<std::string> newparams;
1141                                 newparams.push_back(params[0]);
1142                                 newparams.push_back(ConvToStr(ourTS));
1143                                 newparams.push_back(to_bounce+params_to_bounce);
1144                                 DoOneToOne(Srv->GetServerName(),"FMODE",newparams,sourceserv);
1145                         }
1146
1147                         if (to_keep.length())
1148                         {
1149                                 n = 0;
1150                                 modelist[0] = params[0].c_str();
1151                                 modelist[1] = to_keep.c_str();
1152
1153                                 for (unsigned int q = 2; (q < params.size()) && (q < 64); q++)
1154                                                 modelist[q] = params_to_keep[n++].c_str();
1155
1156                                 if (smode)
1157                                 {
1158                                         Srv->SendMode(modelist, n+2, who);
1159                                 }
1160                                 else
1161                                 {
1162                                         Srv->CallCommandHandler("MODE", modelist, n+2, who);
1163                                 }
1164
1165                                 /* HOT POTATO! PASS IT ON! */
1166                                 DoOneToAllButSender(source,"FMODE",params,sourceserv);
1167                         }
1168                 }
1169                 else
1170                 /* U-lined servers always win regardless of their TS */
1171                 if ((TS > ourTS) && (!Srv->IsUlined(source)))
1172                 {
1173                         /* Bounce the mode back to its sender.* We use our lower TS, so the other end
1174                          * SHOULD accept it, if its clock is right.
1175                          *
1176                          * NOTE: We should check that we arent bouncing anything thats already set at this end.
1177                          * If we are, bounce +ourmode to 'reinforce' it. This prevents desyncs.
1178                          * e.g. They send +l 50, we have +l 10 set. rather than bounce -l 50, we bounce +l 10.
1179                          *
1180                          * Thanks to jilles for pointing out this one-hell-of-an-issue before i even finished
1181                          * writing the code. It took me a while to come up with this solution.
1182                          *
1183                          * XXX: BE SURE YOU UNDERSTAND THIS CODE FULLY BEFORE YOU MESS WITH IT.
1184                          */
1185
1186                         std::deque<std::string> newparams;      /* New parameter list we send back */
1187                         newparams.push_back(params[0]);         /* Target, user or channel */
1188                         newparams.push_back(ConvToStr(ourTS));  /* Timestamp value of the target */
1189                         newparams.push_back("");                /* This contains the mode string. For now
1190                                                                  * it's empty, we fill it below.
1191                                                                  */
1192
1193                         /* Intelligent mode bouncing. Don't just invert, reinforce any modes which are already
1194                          * set to avoid a desync here.
1195                          */
1196                         std::string modebounce = "";
1197                         bool adding = true;
1198                         unsigned int t = 3;
1199                         ModeHandler* mh = NULL;
1200                         char cur_change = 1;
1201                         char old_change = 0;
1202                         for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
1203                         {
1204                                 /* Iterate over all mode chars in the sent set */
1205                                 switch (*x)
1206                                 {
1207                                         /* Adding or subtracting modes? */
1208                                         case '-':
1209                                                 adding = false;
1210                                         break;
1211                                         case '+':
1212                                                 adding = true;
1213                                         break;
1214                                         default:
1215                                                 /* Find the mode handler for this mode */
1216                                                 mh = ServerInstance->ModeGrok->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1217
1218                                                 /* Got a mode handler?
1219                                                  * This also prevents us bouncing modes we have no handler for.
1220                                                  */
1221                                                 if (mh)
1222                                                 {
1223                                                         ModePair ret;
1224                                                         std::string p = "";
1225
1226                                                         /* Does the mode require a parameter right now?
1227                                                          * If it does, fetch it if we can
1228                                                          */
1229                                                         if ((mh->GetNumParams(adding) > 0) && (t < params.size()))
1230                                                                 p = params[t++];
1231
1232                                                         /* Call the ModeSet method to determine if its set with the
1233                                                          * given parameter here or not.
1234                                                          */
1235                                                         ret = mh->ModeSet(smode ? NULL : who, dst, chan, p);
1236
1237                                                         /* XXX: Really. Dont ask.
1238                                                          * Determine from if its set combined with what the current
1239                                                          * 'state' is (adding or not) as to wether we should 'invert'
1240                                                          * or 'reinforce' the mode change
1241                                                          */
1242                                                         (!ret.first ? (adding ? cur_change = '-' : cur_change = '+') : (!adding ? cur_change = '-' : cur_change = '+'));
1243
1244                                                         /* Quickly determine if we have 'flipped' from + to -,
1245                                                          * or - to +, to prevent unneccessary +/- chars in the
1246                                                          * output string that waste bandwidth
1247                                                          */
1248                                                         if (cur_change != old_change)
1249                                                                 modebounce += cur_change;
1250                                                         old_change = cur_change;
1251
1252                                                         /* Add the mode character to the output string */
1253                                                         modebounce += mh->GetModeChar();
1254
1255                                                         /* We got a parameter back from ModeHandler::ModeSet,
1256                                                          * are we supposed to be sending one out right now?
1257                                                          */
1258                                                         if (ret.second.length())
1259                                                         {
1260                                                                 if (mh->GetNumParams(cur_change == '+') > 0)
1261                                                                         /* Yes we're supposed to be sending out
1262                                                                          * the parameter. Make sure it goes
1263                                                                          */
1264                                                                         newparams.push_back(ret.second);
1265                                                         }
1266
1267                                                 }
1268                                         break;
1269                                 }
1270                         }
1271                         
1272                         /* Update the parameters for FMODE with the new 'bounced' string */
1273                         newparams[2] = modebounce;
1274                         /* Only send it back the way it came, no need to send it anywhere else */
1275                         DoOneToOne(Srv->GetServerName(),"FMODE",newparams,sourceserv);
1276                         log(DEBUG,"FMODE bounced intelligently, our TS less than theirs and the other server is NOT a uline.");
1277                 }
1278                 else
1279                 {
1280                         log(DEBUG,"Allow modes, TS lower for sender");
1281                         /* The server was ulined, but something iffy is up with the TS.
1282                          * Sound the alarm bells!
1283                          */
1284                         if ((Srv->IsUlined(sourceserv)) && (TS > ourTS))
1285                         {
1286                                 WriteOpers("\2WARNING!\2 U-Lined server '%s' has bad TS for '%s' (accepted change): \2SYNC YOUR CLOCKS\2 to avoid this notice",sourceserv.c_str(),params[0].c_str());
1287                         }
1288                         /* Allow the mode, route it to either server or user command handling */
1289                         if (smode)
1290                                 Srv->SendMode(modelist,n,who);
1291                         else
1292                                 Srv->CallCommandHandler("MODE", modelist, n, who);
1293
1294                         /* HOT POTATO! PASS IT ON! */
1295                         DoOneToAllButSender(source,"FMODE",params,sourceserv);
1296                 }
1297                 /* Are we supposed to free the userrec? */
1298                 if (smode)
1299                         DELETE(who);
1300
1301                 return true;
1302         }
1303
1304         /* FTOPIC command */
1305         bool ForceTopic(std::string source, std::deque<std::string> &params)
1306         {
1307                 if (params.size() != 4)
1308                         return true;
1309                 time_t ts = atoi(params[1].c_str());
1310                 std::string nsource = source;
1311
1312                 chanrec* c = Srv->FindChannel(params[0]);
1313                 if (c)
1314                 {
1315                         if ((ts >= c->topicset) || (!*c->topic))
1316                         {
1317                                 std::string oldtopic = c->topic;
1318                                 strlcpy(c->topic,params[3].c_str(),MAXTOPIC);
1319                                 strlcpy(c->setby,params[2].c_str(),NICKMAX-1);
1320                                 c->topicset = ts;
1321                                 /* if the topic text is the same as the current topic,
1322                                  * dont bother to send the TOPIC command out, just silently
1323                                  * update the set time and set nick.
1324                                  */
1325                                 if (oldtopic != params[3])
1326                                 {
1327                                         userrec* user = Srv->FindNick(source);
1328                                         if (!user)
1329                                         {
1330                                                 WriteChannelWithServ(source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
1331                                         }
1332                                         else
1333                                         {
1334                                                 WriteChannel(c, user, "TOPIC %s :%s", c->name, c->topic);
1335                                                 nsource = user->server;
1336                                         }
1337                                         /* all done, send it on its way */
1338                                         params[3] = ":" + params[3];
1339                                         DoOneToAllButSender(source,"FTOPIC",params,nsource);
1340                                 }
1341                         }
1342                         
1343                 }
1344
1345                 return true;
1346         }
1347
1348         /* FJOIN, similar to unreal SJOIN */
1349         bool ForceJoin(std::string source, std::deque<std::string> &params)
1350         {
1351                 if (params.size() < 3)
1352                         return true;
1353
1354                 char first[MAXBUF];
1355                 char modestring[MAXBUF];
1356                 char* mode_users[127];
1357                 memset(&mode_users,0,sizeof(mode_users));
1358                 mode_users[0] = first;
1359                 mode_users[1] = modestring;
1360                 strcpy(first,"+");
1361                 unsigned int modectr = 2;
1362                 
1363                 userrec* who = NULL;
1364                 std::string channel = params[0];
1365                 time_t TS = atoi(params[1].c_str());
1366                 char* key = "";
1367                 
1368                 chanrec* chan = Srv->FindChannel(channel);
1369                 if (chan)
1370                 {
1371                         key = chan->key;
1372                 }
1373                 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
1374
1375                 /* default is a high value, which if we dont have this
1376                  * channel will let the other side apply their modes.
1377                  */
1378                 time_t ourTS = time(NULL)+600;
1379                 chanrec* us = Srv->FindChannel(channel);
1380                 if (us)
1381                 {
1382                         ourTS = us->age;
1383                 }
1384
1385                 log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
1386
1387                 /* do this first, so our mode reversals are correctly received by other servers
1388                  * if there is a TS collision.
1389                  */
1390                 DoOneToAllButSender(source,"FJOIN",params,source);
1391                 
1392                 for (unsigned int usernum = 2; usernum < params.size(); usernum++)
1393                 {
1394                         /* process one channel at a time, applying modes. */
1395                         char* usr = (char*)params[usernum].c_str();
1396                         /* Safety check just to make sure someones not sent us an FJOIN full of spaces
1397                          * (is this even possible?) */
1398                         if (usr && *usr)
1399                         {
1400                                 char permissions = *usr;
1401                                 switch (permissions)
1402                                 {
1403                                         case '@':
1404                                                 usr++;
1405                                                 mode_users[modectr++] = usr;
1406                                                 strlcat(modestring,"o",MAXBUF);
1407                                         break;
1408                                         case '%':
1409                                                 usr++;
1410                                                 mode_users[modectr++] = usr;
1411                                                 strlcat(modestring,"h",MAXBUF);
1412                                         break;
1413                                         case '+':
1414                                                 usr++;
1415                                                 mode_users[modectr++] = usr;
1416                                                 strlcat(modestring,"v",MAXBUF);
1417                                         break;
1418                                 }
1419                                 who = Srv->FindNick(usr);
1420                                 if (who)
1421                                 {
1422                                         Srv->JoinUserToChannel(who,channel,key);
1423                                         if (modectr >= (MAXMODES-1))
1424                                         {
1425                                                 /* theres a mode for this user. push them onto the mode queue, and flush it
1426                                                  * if there are more than MAXMODES to go.
1427                                                  */
1428                                                 if ((ourTS >= TS) || (Srv->IsUlined(who->server)))
1429                                                 {
1430                                                         /* We also always let u-lined clients win, no matter what the TS value */
1431                                                         log(DEBUG,"Our our channel newer than theirs, accepting their modes");
1432                                                         Srv->SendMode((const char**)mode_users,modectr,who);
1433                                                         if (ourTS != TS)
1434                                                         {
1435                                                                 log(DEFAULT,"Channel TS for %s changed from %lu to %lu",us,ourTS,TS);
1436                                                                 us->age = TS;
1437                                                         }
1438                                                 }
1439                                                 else
1440                                                 {
1441                                                         log(DEBUG,"Their channel newer than ours, bouncing their modes");
1442                                                         /* bouncy bouncy! */
1443                                                         std::deque<std::string> params;
1444                                                         /* modes are now being UNSET... */
1445                                                         *mode_users[1] = '-';
1446                                                         for (unsigned int x = 0; x < modectr; x++)
1447                                                         {
1448                                                                 if (x == 1)
1449                                                                 {
1450                                                                         params.push_back(ConvToStr(us->age));
1451                                                                 }
1452                                                                 params.push_back(mode_users[x]);
1453                                                         }
1454                                                         // tell everyone to bounce the modes. bad modes, bad!
1455                                                         DoOneToMany(Srv->GetServerName(),"FMODE",params);
1456                                                 }
1457                                                 strcpy(mode_users[1],"+");
1458                                                 modectr = 2;
1459                                         }
1460                                 }
1461                         }
1462                 }
1463                 /* there werent enough modes built up to flush it during FJOIN,
1464                  * or, there are a number left over. flush them out.
1465                  */
1466                 if ((modectr > 2) && (who))
1467                 {
1468                         if (ourTS >= TS)
1469                         {
1470                                 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
1471                                 Srv->SendMode((const char**)mode_users,modectr,who);
1472                                 if (ourTS != TS)
1473                                 {
1474                                         log(DEFAULT,"Channel TS for %s changed from %lu to %lu",us,ourTS,TS);
1475                                         us->age = TS;
1476                                 }
1477                         }
1478                         else
1479                         {
1480                                 log(DEBUG,"Their channel newer than ours, bouncing their modes");
1481                                 std::deque<std::string> params;
1482                                 *mode_users[1] = '-';
1483                                 for (unsigned int x = 0; x < modectr; x++)
1484                                 {
1485                                         if (x == 1)
1486                                         {
1487                                                 params.push_back(ConvToStr(us->age));
1488                                         }
1489                                         params.push_back(mode_users[x]);
1490                                 }
1491                                 DoOneToMany(Srv->GetServerName(),"FMODE",params);
1492                         }
1493                 }
1494                 return true;
1495         }
1496
1497         bool SyncChannelTS(std::string source, std::deque<std::string> &params)
1498         {
1499                 if (params.size() >= 2)
1500                 {
1501                         chanrec* c = Srv->FindChannel(params[0]);
1502                         if (c)
1503                         {
1504                                 time_t theirTS = atoi(params[1].c_str());
1505                                 time_t ourTS = c->age;
1506                                 if (ourTS >= theirTS)
1507                                 {
1508                                         log(DEBUG,"Updating timestamp for %s, our timestamp was %lu and theirs is %lu",c->name,ourTS,theirTS);
1509                                         c->age = theirTS;
1510                                 }
1511                         }
1512                 }
1513                 DoOneToAllButSender(Srv->GetServerName(),"SYNCTS",params,source);
1514                 return true;
1515         }
1516
1517         /* NICK command */
1518         bool IntroduceClient(std::string source, std::deque<std::string> &params)
1519         {
1520                 if (params.size() < 8)
1521                         return true;
1522                 if (params.size() > 8)
1523                 {
1524                         this->WriteLine(":"+Srv->GetServerName()+" KILL "+params[1]+" :Invalid client introduction ("+params[1]+"?)");
1525                         return true;
1526                 }
1527                 // NICK age nick host dhost ident +modes ip :gecos
1528                 //   0   123  4 56   7
1529                 time_t age = atoi(params[0].c_str());
1530                 
1531                 /* This used to have a pretty craq'y loop doing the same thing,
1532                  * now we just let the STL do the hard work (more efficiently)
1533                  */
1534                 params[5] = params[5].substr(params[5].find_first_not_of('+'));
1535                 
1536                 const char* tempnick = params[1].c_str();
1537                 log(DEBUG,"Introduce client %s!%s@%s",tempnick,params[4].c_str(),params[2].c_str());
1538                 
1539                 user_hash::iterator iter = clientlist.find(tempnick);
1540                 
1541                 if (iter != clientlist.end())
1542                 {
1543                         // nick collision
1544                         log(DEBUG,"Nick collision on %s!%s@%s: %lu %lu",tempnick,params[4].c_str(),params[2].c_str(),(unsigned long)age,(unsigned long)iter->second->age);
1545                         this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
1546                         return true;
1547                 }
1548
1549                 clientlist[tempnick] = new userrec();
1550                 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
1551                 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX-1);
1552                 strlcpy(clientlist[tempnick]->host, params[2].c_str(),63);
1553                 strlcpy(clientlist[tempnick]->dhost, params[3].c_str(),63);
1554                 clientlist[tempnick]->server = FindServerNamePtr(source.c_str());
1555                 strlcpy(clientlist[tempnick]->ident, params[4].c_str(),IDENTMAX);
1556                 strlcpy(clientlist[tempnick]->fullname, params[7].c_str(),MAXGECOS);
1557                 clientlist[tempnick]->registered = REG_ALL;
1558                 clientlist[tempnick]->signon = age;
1559                 
1560                 for (std::string::iterator v = params[5].begin(); v != params[5].end(); v++)
1561                 {
1562                         clientlist[tempnick]->modes[(*v)-65] = 1;
1563                 }
1564                 insp_aton(params[6].c_str(),&clientlist[tempnick]->ip4);
1565
1566                 WriteOpers("*** Client connecting at %s: %s!%s@%s [%s]",clientlist[tempnick]->server,clientlist[tempnick]->nick,clientlist[tempnick]->ident,clientlist[tempnick]->host, insp_ntoa(clientlist[tempnick]->ip4));
1567
1568                 params[7] = ":" + params[7];
1569                 DoOneToAllButSender(source,"NICK",params,source);
1570
1571                 // Increment the Source Servers User Count..
1572                 TreeServer* SourceServer = FindServer(source);
1573                 if (SourceServer)
1574                 {
1575                         log(DEBUG,"Found source server of %s",clientlist[tempnick]->nick);
1576                         SourceServer->AddUserCount();
1577                 }
1578
1579                 return true;
1580         }
1581
1582         /* Send one or more FJOINs for a channel of users.
1583          * If the length of a single line is more than 480-NICKMAX
1584          * in length, it is split over multiple lines.
1585          */
1586         void SendFJoins(TreeServer* Current, chanrec* c)
1587         {
1588                 log(DEBUG,"Sending FJOINs to other server for %s",c->name);
1589                 char list[MAXBUF];
1590                 std::string individual_halfops = ":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age);
1591                 
1592                 size_t dlen, curlen;
1593                 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1594                 int numusers = 0;
1595                 char* ptr = list + dlen;
1596
1597                 CUList *ulist = c->GetUsers();
1598                 std::vector<userrec*> specific_halfop;
1599                 std::vector<userrec*> specific_voice;
1600                 std::string modes = "";
1601                 std::string params = "";
1602
1603                 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1604                 {
1605                         int x = cflags(i->second,c);
1606                         if ((x & UCMODE_HOP) && (x & UCMODE_OP))
1607                         {
1608                                 specific_halfop.push_back(i->second);
1609                         }
1610                         if (((x & UCMODE_HOP) || (x & UCMODE_OP)) && (x & UCMODE_VOICE))
1611                         {
1612                                 specific_voice.push_back(i->second);
1613                         }
1614
1615                         const char* n = "";
1616                         if (x & UCMODE_OP)
1617                         {
1618                                 n = "@";
1619                         }
1620                         else if (x & UCMODE_HOP)
1621                         {
1622                                 n = "%";
1623                         }
1624                         else if (x & UCMODE_VOICE)
1625                         {
1626                                 n = "+";
1627                         }
1628
1629                         size_t ptrlen = snprintf(ptr, MAXBUF, " %s%s", n, i->second->nick);
1630
1631                         curlen += ptrlen;
1632                         ptr += ptrlen;
1633
1634                         numusers++;
1635
1636                         if (curlen > (480-NICKMAX))
1637                         {
1638                                 this->WriteLine(list);
1639                                 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1640                                 ptr = list + dlen;
1641                                 ptrlen = 0;
1642                                 numusers = 0;
1643                                 for (unsigned int y = 0; y < specific_voice.size(); y++)
1644                                 {
1645                                         modes.append("v");
1646                                         params.append(specific_voice[y]->nick).append(" ");
1647                                         //this->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" +v "+specific_voice[y]->nick);
1648                                 }
1649                                 for (unsigned int y = 0; y < specific_halfop.size(); y++)
1650                                 {
1651                                         modes.append("h");
1652                                         params.append(specific_halfop[y]->nick).append(" ");
1653                                         //this->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" +h "+specific_halfop[y]->nick);
1654                                 }
1655                         }
1656                 }
1657                 if (numusers)
1658                 {
1659                         this->WriteLine(list);
1660                         for (unsigned int y = 0; y < specific_voice.size(); y++)
1661                         {
1662                                 modes.append("v");
1663                                 params.append(specific_voice[y]->nick).append(" ");
1664                                 //this->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" +v "+specific_voice[y]->nick);
1665                         }
1666                         for (unsigned int y = 0; y < specific_halfop.size(); y++)
1667                         {
1668                                 modes.append("h");
1669                                 params.append(specific_halfop[y]->nick).append(" ");
1670                                 //this->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" +h "+specific_halfop[y]->nick);
1671                         }
1672                 }
1673                 //std::string modes = "";
1674                 //std::string params = "";
1675                 for (BanList::iterator b = c->bans.begin(); b != c->bans.end(); b++)
1676                 {
1677                         modes.append("b");
1678                         params.append(b->data).append(" ");
1679                 }
1680                 /* XXX: Send each channel mode and its params -- we'll need a method for this in ModeHandler? */
1681                 //FOREACH_MOD(I_OnSyncChannel,OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this));
1682                 this->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" +"+chanmodes(c,true)+modes+" "+params);
1683         }
1684
1685         /* Send G, Q, Z and E lines */
1686         void SendXLines(TreeServer* Current)
1687         {
1688                 char data[MAXBUF];
1689                 std::string n = Srv->GetServerName();
1690                 const char* sn = n.c_str();
1691                 int iterations = 0;
1692                 /* Yes, these arent too nice looking, but they get the job done */
1693                 for (std::vector<ZLine>::iterator i = zlines.begin(); i != zlines.end(); i++, iterations++)
1694                 {
1695                         snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s",sn,i->ipaddr,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1696                         this->WriteLine(data);
1697                 }
1698                 for (std::vector<QLine>::iterator i = qlines.begin(); i != qlines.end(); i++, iterations++)
1699                 {
1700                         snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s",sn,i->nick,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1701                         this->WriteLine(data);
1702                 }
1703                 for (std::vector<GLine>::iterator i = glines.begin(); i != glines.end(); i++, iterations++)
1704                 {
1705                         snprintf(data,MAXBUF,":%s ADDLINE G %s %s %lu %lu :%s",sn,i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1706                         this->WriteLine(data);
1707                 }
1708                 for (std::vector<ELine>::iterator i = elines.begin(); i != elines.end(); i++, iterations++)
1709                 {
1710                         snprintf(data,MAXBUF,":%s ADDLINE E %s %s %lu %lu :%s",sn,i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1711                         this->WriteLine(data);
1712                 }
1713                 for (std::vector<ZLine>::iterator i = pzlines.begin(); i != pzlines.end(); i++, iterations++)
1714                 {
1715                         snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s",sn,i->ipaddr,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1716                         this->WriteLine(data);
1717                 }
1718                 for (std::vector<QLine>::iterator i = pqlines.begin(); i != pqlines.end(); i++, iterations++)
1719                 {
1720                         snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s",sn,i->nick,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1721                         this->WriteLine(data);
1722                 }
1723                 for (std::vector<GLine>::iterator i = pglines.begin(); i != pglines.end(); i++, iterations++)
1724                 {
1725                         snprintf(data,MAXBUF,":%s ADDLINE G %s %s %lu %lu :%s",sn,i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1726                         this->WriteLine(data);
1727                 }
1728                 for (std::vector<ELine>::iterator i = pelines.begin(); i != pelines.end(); i++, iterations++)
1729                 {
1730                         snprintf(data,MAXBUF,":%s ADDLINE E %s %s %lu %lu :%s",sn,i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1731                         this->WriteLine(data);
1732                 }
1733         }
1734
1735         /* Send channel modes and topics */
1736         void SendChannelModes(TreeServer* Current)
1737         {
1738                 char data[MAXBUF];
1739                 std::deque<std::string> list;
1740                 int iterations = 0;
1741                 std::string n = Srv->GetServerName();
1742                 const char* sn = n.c_str();
1743                 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++, iterations++)
1744                 {
1745                         SendFJoins(Current, c->second);
1746                         if (*c->second->topic)
1747                         {
1748                                 snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",sn,c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
1749                                 this->WriteLine(data);
1750                         }
1751                         FOREACH_MOD(I_OnSyncChannel,OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this));
1752                         list.clear();
1753                         c->second->GetExtList(list);
1754                         for (unsigned int j = 0; j < list.size(); j++)
1755                         {
1756                                 FOREACH_MOD(I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
1757                         }
1758                 }
1759         }
1760
1761         /* send all users and their oper state/modes */
1762         void SendUsers(TreeServer* Current)
1763         {
1764                 char data[MAXBUF];
1765                 std::deque<std::string> list;
1766                 int iterations = 0;
1767                 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++, iterations++)
1768                 {
1769                         if (u->second->registered == REG_ALL)
1770                         {
1771                                 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->FormatModes(),insp_ntoa(u->second->ip4),u->second->fullname);
1772                                 this->WriteLine(data);
1773                                 if (*u->second->oper)
1774                                 {
1775                                         this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
1776                                 }
1777                                 if (*u->second->awaymsg)
1778                                 {
1779                                         this->WriteLine(":"+std::string(u->second->nick)+" AWAY :"+std::string(u->second->awaymsg));
1780                                 }
1781                                 FOREACH_MOD(I_OnSyncUser,OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this));
1782                                 list.clear();
1783                                 u->second->GetExtList(list);
1784                                 for (unsigned int j = 0; j < list.size(); j++)
1785                                 {
1786                                         FOREACH_MOD(I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
1787                                 }
1788                         }
1789                 }
1790         }
1791
1792         /* This function is called when we want to send a netburst to a local
1793          * server. There is a set order we must do this, because for example
1794          * users require their servers to exist, and channels require their
1795          * users to exist. You get the idea.
1796          */
1797         void DoBurst(TreeServer* s)
1798         {
1799                 /* The calls here to ServerInstance-> yield the processing
1800                  * back to the core so that a large burst is split into at least 6 sections
1801                  * (possibly more)
1802                  */
1803                 std::string burst = "BURST "+ConvToStr(time(NULL));
1804                 std::string endburst = "ENDBURST";
1805                 // Because by the end of the netburst, it  could be gone!
1806                 std::string name = s->GetName();
1807                 Srv->SendOpers("*** Bursting to \2"+name+"\2.");
1808                 this->WriteLine(burst);
1809                 /* send our version string */
1810                 this->WriteLine(":"+Srv->GetServerName()+" VERSION :"+Srv->GetVersion());
1811                 /* Send server tree */
1812                 this->SendServers(TreeRoot,s,1);
1813                 /* Send users and their oper status */
1814                 this->SendUsers(s);
1815                 /* Send everything else (channel modes, xlines etc) */
1816                 this->SendChannelModes(s);
1817                 this->SendXLines(s);            
1818                 FOREACH_MOD(I_OnSyncOtherMetaData,OnSyncOtherMetaData((Module*)TreeProtocolModule,(void*)this));
1819                 this->WriteLine(endburst);
1820                 Srv->SendOpers("*** Finished bursting to \2"+name+"\2.");
1821         }
1822
1823         /* This function is called when we receive data from a remote
1824          * server. We buffer the data in a std::string (it doesnt stay
1825          * there for long), reading using InspSocket::Read() which can
1826          * read up to 16 kilobytes in one operation.
1827          *
1828          * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
1829          * THE SOCKET OBJECT FOR US.
1830          */
1831         virtual bool OnDataReady()
1832         {
1833                 char* data = this->Read();
1834                 /* Check that the data read is a valid pointer and it has some content */
1835                 if (data && *data)
1836                 {
1837                         this->in_buffer.append(data);
1838                         /* While there is at least one new line in the buffer,
1839                          * do something useful (we hope!) with it.
1840                          */
1841                         while (in_buffer.find("\n") != std::string::npos)
1842                         {
1843                                 std::string ret = in_buffer.substr(0,in_buffer.find("\n")-1);
1844                                 in_buffer = in_buffer.substr(in_buffer.find("\n")+1,in_buffer.length()-in_buffer.find("\n"));
1845                                 if (ret.find("\r") != std::string::npos)
1846                                         ret = in_buffer.substr(0,in_buffer.find("\r")-1);
1847                                 /* Process this one, abort if it
1848                                  * didnt return true.
1849                                  */
1850                                 if (this->ctx_in)
1851                                 {
1852                                         char out[1024];
1853                                         char result[1024];
1854                                         memset(result,0,1024);
1855                                         memset(out,0,1024);
1856                                         log(DEBUG,"Original string '%s'",ret.c_str());
1857                                         /* ERROR + CAPAB is still allowed unencryped */
1858                                         if ((ret.substr(0,7) != "ERROR :") && (ret.substr(0,6) != "CAPAB "))
1859                                         {
1860                                                 int nbytes = from64tobits(out, ret.c_str(), 1024);
1861                                                 if ((nbytes > 0) && (nbytes < 1024))
1862                                                 {
1863                                                         log(DEBUG,"m_spanningtree: decrypt %d bytes",nbytes);
1864                                                         ctx_in->Decrypt(out, result, nbytes, 0);
1865                                                         for (int t = 0; t < nbytes; t++)
1866                                                                 if (result[t] == '\7') result[t] = 0;
1867                                                         ret = result;
1868                                                 }
1869                                         }
1870                                 }
1871                                 if (!this->ProcessLine(ret))
1872                                 {
1873                                         log(DEBUG,"ProcessLine says no!");
1874                                         return false;
1875                                 }
1876                         }
1877                         return true;
1878                 }
1879                 /* EAGAIN returns an empty but non-NULL string, so this
1880                  * evaluates to TRUE for EAGAIN but to FALSE for EOF.
1881                  */
1882                 return (data && !*data);
1883         }
1884
1885         int WriteLine(std::string line)
1886         {
1887                 log(DEBUG,"OUT: %s",line.c_str());
1888                 if (this->ctx_out)
1889                 {
1890                         char result[10240];
1891                         char result64[10240];
1892                         if (this->keylength)
1893                         {
1894                                 // pad it to the key length
1895                                 int n = this->keylength - (line.length() % this->keylength);
1896                                 if (n)
1897                                 {
1898                                         log(DEBUG,"Append %d chars to line to make it %d long from %d, key length %d",n,n+line.length(),line.length(),this->keylength);
1899                                         line.append(n,'\7');
1900                                 }
1901                         }
1902                         unsigned int ll = line.length();
1903                         ctx_out->Encrypt(line.c_str(), result, ll, 0);
1904                         to64frombits((unsigned char*)result64,(unsigned char*)result,ll);
1905                         line = result64;
1906                         //int from64tobits(char *out, const char *in, int maxlen);
1907                 }
1908                 return this->Write(line + "\r\n");
1909         }
1910
1911         /* Handle ERROR command */
1912         bool Error(std::deque<std::string> &params)
1913         {
1914                 if (params.size() < 1)
1915                         return false;
1916                 WriteOpers("*** ERROR from %s: %s",(InboundServerName != "" ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
1917                 /* we will return false to cause the socket to close. */
1918                 return false;
1919         }
1920
1921         bool Stats(std::string prefix, std::deque<std::string> &params)
1922         {
1923                 /* Get the reply to a STATS query if it matches this servername,
1924                  * and send it back as a load of PUSH queries
1925                  */
1926                 if (params.size() > 1)
1927                 {
1928                         if (Srv->MatchText(Srv->GetServerName(), params[1]))
1929                         {
1930                                 /* It's for our server */
1931                                 string_list results;
1932                                 userrec* source = Srv->FindNick(prefix);
1933                                 if (source)
1934                                 {
1935                                         std::deque<std::string> par;
1936                                         par.push_back(prefix);
1937                                         par.push_back("");
1938                                         DoStats(*(params[0].c_str()), source, results);
1939                                         for (size_t i = 0; i < results.size(); i++)
1940                                         {
1941                                                 par[1] = "::" + results[i];
1942                                                 DoOneToOne(Srv->GetServerName(), "PUSH",par, source->server);
1943                                         }
1944                                 }
1945                         }
1946                         else
1947                         {
1948                                 /* Pass it on */
1949                                 userrec* source = Srv->FindNick(prefix);
1950                                 if (source)
1951                                         DoOneToOne(prefix, "STATS", params, params[1]);
1952                         }
1953                 }
1954                 return true;
1955         }
1956
1957
1958         /* Because the core won't let users or even SERVERS set +o,
1959          * we use the OPERTYPE command to do this.
1960          */
1961         bool OperType(std::string prefix, std::deque<std::string> &params)
1962         {
1963                 if (params.size() != 1)
1964                 {
1965                         log(DEBUG,"Received invalid oper type from %s",prefix.c_str());
1966                         return true;
1967                 }
1968                 std::string opertype = params[0];
1969                 userrec* u = Srv->FindNick(prefix);
1970                 if (u)
1971                 {
1972                         u->modes[UM_OPERATOR] = 1;
1973                         strlcpy(u->oper,opertype.c_str(),NICKMAX-1);
1974                         DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
1975                 }
1976                 return true;
1977         }
1978
1979         /* Because Andy insists that services-compatible servers must
1980          * implement SVSNICK and SVSJOIN, that's exactly what we do :p
1981          */
1982         bool ForceNick(std::string prefix, std::deque<std::string> &params)
1983         {
1984                 if (params.size() < 3)
1985                         return true;
1986
1987                 userrec* u = Srv->FindNick(params[0]);
1988
1989                 if (u)
1990                 {
1991                         DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
1992                         if (IS_LOCAL(u))
1993                         {
1994                                 std::deque<std::string> par;
1995                                 par.push_back(params[1]);
1996                                 /* This is not required as one is sent in OnUserPostNick below
1997                                  */
1998                                 //DoOneToMany(u->nick,"NICK",par);
1999                                 Srv->ChangeUserNick(u,params[1]);
2000                                 u->age = atoi(params[2].c_str());
2001                         }
2002                 }
2003                 return true;
2004         }
2005
2006         bool ServiceJoin(std::string prefix, std::deque<std::string> &params)
2007         {
2008                 if (params.size() < 2)
2009                         return true;
2010
2011                 userrec* u = Srv->FindNick(params[0]);
2012
2013                 if (u)
2014                 {
2015                         Srv->JoinUserToChannel(u,params[1],"");
2016                         DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
2017                 }
2018                 return true;
2019         }
2020
2021         bool RemoteRehash(std::string prefix, std::deque<std::string> &params)
2022         {
2023                 if (params.size() < 1)
2024                         return false;
2025
2026                 std::string servermask = params[0];
2027
2028                 if (Srv->MatchText(Srv->GetServerName(),servermask))
2029                 {
2030                         Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
2031                         Srv->RehashServer();
2032                         ReadConfiguration(false);
2033                 }
2034                 DoOneToAllButSender(prefix,"REHASH",params,prefix);
2035                 return true;
2036         }
2037
2038         bool RemoteKill(std::string prefix, std::deque<std::string> &params)
2039         {
2040                 if (params.size() != 2)
2041                         return true;
2042
2043                 std::string nick = params[0];
2044                 userrec* u = Srv->FindNick(prefix);
2045                 userrec* who = Srv->FindNick(nick);
2046
2047                 if (who)
2048                 {
2049                         /* Prepend kill source, if we don't have one */
2050                         std::string sourceserv = prefix;
2051                         if (u)
2052                         {
2053                                 sourceserv = u->server;
2054                         }
2055                         if (*(params[1].c_str()) != '[')
2056                         {
2057                                 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
2058                         }
2059                         std::string reason = params[1];
2060                         params[1] = ":" + params[1];
2061                         DoOneToAllButSender(prefix,"KILL",params,sourceserv);
2062                         ::Write(who->fd, ":%s KILL %s :%s (%s)", sourceserv.c_str(), who->nick, sourceserv.c_str(), reason.c_str());
2063                         Srv->QuitUser(who,reason);
2064                 }
2065                 return true;
2066         }
2067
2068         bool LocalPong(std::string prefix, std::deque<std::string> &params)
2069         {
2070                 if (params.size() < 1)
2071                         return true;
2072
2073                 if (params.size() == 1)
2074                 {
2075                         TreeServer* ServerSource = FindServer(prefix);
2076                         if (ServerSource)
2077                         {
2078                                 ServerSource->SetPingFlag();
2079                         }
2080                 }
2081                 else
2082                 {
2083                         std::string forwardto = params[1];
2084                         if (forwardto == Srv->GetServerName())
2085                         {
2086                                 /*
2087                                  * this is a PONG for us
2088                                  * if the prefix is a user, check theyre local, and if they are,
2089                                  * dump the PONG reply back to their fd. If its a server, do nowt.
2090                                  * Services might want to send these s->s, but we dont need to yet.
2091                                  */
2092                                 userrec* u = Srv->FindNick(prefix);
2093
2094                                 if (u)
2095                                 {
2096                                         WriteServ(u->fd,"PONG %s %s",params[0].c_str(),params[1].c_str());
2097                                 }
2098                         }
2099                         else
2100                         {
2101                                 // not for us, pass it on :)
2102                                 DoOneToOne(prefix,"PONG",params,forwardto);
2103                         }
2104                 }
2105
2106                 return true;
2107         }
2108         
2109         bool MetaData(std::string prefix, std::deque<std::string> &params)
2110         {
2111                 if (params.size() < 3)
2112                         return true;
2113
2114                 TreeServer* ServerSource = FindServer(prefix);
2115
2116                 if (ServerSource)
2117                 {
2118                         if (params[0] == "*")
2119                         {
2120                                 FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
2121                         }
2122                         else if (*(params[0].c_str()) == '#')
2123                         {
2124                                 chanrec* c = Srv->FindChannel(params[0]);
2125                                 if (c)
2126                                 {
2127                                         FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
2128                                 }
2129                         }
2130                         else if (*(params[0].c_str()) != '#')
2131                         {
2132                                 userrec* u = Srv->FindNick(params[0]);
2133                                 if (u)
2134                                 {
2135                                         FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
2136                                 }
2137                         }
2138                 }
2139
2140                 params[2] = ":" + params[2];
2141                 DoOneToAllButSender(prefix,"METADATA",params,prefix);
2142                 return true;
2143         }
2144
2145         bool ServerVersion(std::string prefix, std::deque<std::string> &params)
2146         {
2147                 if (params.size() < 1)
2148                         return true;
2149
2150                 TreeServer* ServerSource = FindServer(prefix);
2151
2152                 if (ServerSource)
2153                 {
2154                         ServerSource->SetVersion(params[0]);
2155                 }
2156                 params[0] = ":" + params[0];
2157                 DoOneToAllButSender(prefix,"VERSION",params,prefix);
2158                 return true;
2159         }
2160
2161         bool ChangeHost(std::string prefix, std::deque<std::string> &params)
2162         {
2163                 if (params.size() < 1)
2164                         return true;
2165
2166                 userrec* u = Srv->FindNick(prefix);
2167
2168                 if (u)
2169                 {
2170                         Srv->ChangeHost(u,params[0]);
2171                         DoOneToAllButSender(prefix,"FHOST",params,u->server);
2172                 }
2173                 return true;
2174         }
2175
2176         bool AddLine(std::string prefix, std::deque<std::string> &params)
2177         {
2178                 if (params.size() < 6)
2179                         return true;
2180
2181                 bool propogate = false;
2182
2183                 switch (*(params[0].c_str()))
2184                 {
2185                         case 'Z':
2186                                 propogate = add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2187                                 zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2188                         break;
2189                         case 'Q':
2190                                 propogate = add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2191                                 qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2192                         break;
2193                         case 'E':
2194                                 propogate = add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2195                                 eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2196                         break;
2197                         case 'G':
2198                                 propogate = add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2199                                 gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2200                         break;
2201                         case 'K':
2202                                 propogate = add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2203                         break;
2204                         default:
2205                                 /* Just in case... */
2206                                 Srv->SendOpers("*** \2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");
2207                                 propogate = false;
2208                         break;
2209                 }
2210
2211                 /* Send it on its way */
2212                 if (propogate)
2213                 {
2214                         if (atoi(params[4].c_str()))
2215                         {
2216                                 WriteOpers("*** %s Added %cLINE on %s to expire in %lu seconds (%s).",prefix.c_str(),*(params[0].c_str()),params[1].c_str(),atoi(params[4].c_str()),params[5].c_str());
2217                         }
2218                         else
2219                         {
2220                                 WriteOpers("*** %s Added permenant %cLINE on %s (%s).",prefix.c_str(),*(params[0].c_str()),params[1].c_str(),params[5].c_str());
2221                         }
2222                         params[5] = ":" + params[5];
2223                         DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
2224                 }
2225                 if (!this->bursting)
2226                 {
2227                         log(DEBUG,"Applying lines...");
2228                         apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2229                 }
2230                 return true;
2231         }
2232
2233         bool ChangeName(std::string prefix, std::deque<std::string> &params)
2234         {
2235                 if (params.size() < 1)
2236                         return true;
2237
2238                 userrec* u = Srv->FindNick(prefix);
2239
2240                 if (u)
2241                 {
2242                         Srv->ChangeGECOS(u,params[0]);
2243                         params[0] = ":" + params[0];
2244                         DoOneToAllButSender(prefix,"FNAME",params,u->server);
2245                 }
2246                 return true;
2247         }
2248
2249         bool Whois(std::string prefix, std::deque<std::string> &params)
2250         {
2251                 if (params.size() < 1)
2252                         return true;
2253
2254                 log(DEBUG,"In IDLE command");
2255                 userrec* u = Srv->FindNick(prefix);
2256
2257                 if (u)
2258                 {
2259                         log(DEBUG,"USER EXISTS: %s",u->nick);
2260                         // an incoming request
2261                         if (params.size() == 1)
2262                         {
2263                                 userrec* x = Srv->FindNick(params[0]);
2264                                 if ((x) && (IS_LOCAL(x)))
2265                                 {
2266                                         userrec* x = Srv->FindNick(params[0]);
2267                                         log(DEBUG,"Got IDLE");
2268                                         char signon[MAXBUF];
2269                                         char idle[MAXBUF];
2270                                         log(DEBUG,"Sending back IDLE 3");
2271                                         snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
2272                                         snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-time(NULL)));
2273                                         std::deque<std::string> par;
2274                                         par.push_back(prefix);
2275                                         par.push_back(signon);
2276                                         par.push_back(idle);
2277                                         // ours, we're done, pass it BACK
2278                                         DoOneToOne(params[0],"IDLE",par,u->server);
2279                                 }
2280                                 else
2281                                 {
2282                                         // not ours pass it on
2283                                         DoOneToOne(prefix,"IDLE",params,x->server);
2284                                 }
2285                         }
2286                         else if (params.size() == 3)
2287                         {
2288                                 std::string who_did_the_whois = params[0];
2289                                 userrec* who_to_send_to = Srv->FindNick(who_did_the_whois);
2290                                 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2291                                 {
2292                                         log(DEBUG,"Got final IDLE");
2293                                         // an incoming reply to a whois we sent out
2294                                         std::string nick_whoised = prefix;
2295                                         unsigned long signon = atoi(params[1].c_str());
2296                                         unsigned long idle = atoi(params[2].c_str());
2297                                         if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2298                                                 do_whois(who_to_send_to,u,signon,idle,nick_whoised.c_str());
2299                                 }
2300                                 else
2301                                 {
2302                                         // not ours, pass it on
2303                                         DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
2304                                 }
2305                         }
2306                 }
2307                 return true;
2308         }
2309
2310         bool Push(std::string prefix, std::deque<std::string> &params)
2311         {
2312                 if (params.size() < 2)
2313                         return true;
2314
2315                 userrec* u = Srv->FindNick(params[0]);
2316
2317                 if (!u)
2318                         return true;
2319
2320                 if (IS_LOCAL(u))
2321                 {
2322                         ::Write(u->fd,"%s",params[1].c_str());
2323                 }
2324                 else
2325                 {
2326                         // continue the raw onwards
2327                         params[1] = ":" + params[1];
2328                         DoOneToOne(prefix,"PUSH",params,u->server);
2329                 }
2330                 return true;
2331         }
2332
2333         bool Time(std::string prefix, std::deque<std::string> &params)
2334         {
2335                 // :source.server TIME remote.server sendernick
2336                 // :remote.server TIME source.server sendernick TS
2337                 if (params.size() == 2)
2338                 {
2339                         // someone querying our time?
2340                         if (Srv->GetServerName() == params[0])
2341                         {
2342                                 userrec* u = Srv->FindNick(params[1]);
2343                                 if (u)
2344                                 {
2345                                         char curtime[256];
2346                                         snprintf(curtime,256,"%lu",(unsigned long)time(NULL));
2347                                         params.push_back(curtime);
2348                                         params[0] = prefix;
2349                                         DoOneToOne(Srv->GetServerName(),"TIME",params,params[0]);
2350                                 }
2351                         }
2352                         else
2353                         {
2354                                 // not us, pass it on
2355                                 userrec* u = Srv->FindNick(params[1]);
2356                                 if (u)
2357                                         DoOneToOne(prefix,"TIME",params,params[0]);
2358                         }
2359                 }
2360                 else if (params.size() == 3)
2361                 {
2362                         // a response to a previous TIME
2363                         userrec* u = Srv->FindNick(params[1]);
2364                         if ((u) && (IS_LOCAL(u)))
2365                         {
2366                         time_t rawtime = atol(params[2].c_str());
2367                         struct tm * timeinfo;
2368                         timeinfo = localtime(&rawtime);
2369                                 char tms[26];
2370                                 snprintf(tms,26,"%s",asctime(timeinfo));
2371                                 tms[24] = 0;
2372                         WriteServ(u->fd,"391 %s %s :%s",u->nick,prefix.c_str(),tms);
2373                         }
2374                         else
2375                         {
2376                                 if (u)
2377                                         DoOneToOne(prefix,"TIME",params,u->server);
2378                         }
2379                 }
2380                 return true;
2381         }
2382         
2383         bool LocalPing(std::string prefix, std::deque<std::string> &params)
2384         {
2385                 if (params.size() < 1)
2386                         return true;
2387
2388                 if (params.size() == 1)
2389                 {
2390                         std::string stufftobounce = params[0];
2391                         this->WriteLine(":"+Srv->GetServerName()+" PONG "+stufftobounce);
2392                         return true;
2393                 }
2394                 else
2395                 {
2396                         std::string forwardto = params[1];
2397                         if (forwardto == Srv->GetServerName())
2398                         {
2399                                 // this is a ping for us, send back PONG to the requesting server
2400                                 params[1] = params[0];
2401                                 params[0] = forwardto;
2402                                 DoOneToOne(forwardto,"PONG",params,params[1]);
2403                         }
2404                         else
2405                         {
2406                                 // not for us, pass it on :)
2407                                 DoOneToOne(prefix,"PING",params,forwardto);
2408                         }
2409                         return true;
2410                 }
2411         }
2412
2413         bool RemoteServer(std::string prefix, std::deque<std::string> &params)
2414         {
2415                 if (params.size() < 4)
2416                         return false;
2417
2418                 std::string servername = params[0];
2419                 std::string password = params[1];
2420                 // hopcount is not used for a remote server, we calculate this ourselves
2421                 std::string description = params[3];
2422                 TreeServer* ParentOfThis = FindServer(prefix);
2423
2424                 if (!ParentOfThis)
2425                 {
2426                         this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
2427                         return false;
2428                 }
2429                 TreeServer* CheckDupe = FindServer(servername);
2430                 if (CheckDupe)
2431                 {
2432                         this->WriteLine("ERROR :Server "+servername+" already exists!");
2433                         Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists");
2434                         return false;
2435                 }
2436                 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
2437                 ParentOfThis->AddChild(Node);
2438                 params[3] = ":" + params[3];
2439                 DoOneToAllButSender(prefix,"SERVER",params,prefix);
2440                 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
2441                 return true;
2442         }
2443
2444         bool Outbound_Reply_Server(std::deque<std::string> &params)
2445         {
2446                 if (params.size() < 4)
2447                         return false;
2448
2449                 irc::string servername = params[0].c_str();
2450                 std::string sname = params[0];
2451                 std::string password = params[1];
2452                 int hops = atoi(params[2].c_str());
2453
2454                 if (hops)
2455                 {
2456                         this->WriteLine("ERROR :Server too far away for authentication");
2457                         Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2458                         return false;
2459                 }
2460                 std::string description = params[3];
2461                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2462                 {
2463                         if ((x->Name == servername) && (x->RecvPass == password))
2464                         {
2465                                 TreeServer* CheckDupe = FindServer(sname);
2466                                 if (CheckDupe)
2467                                 {
2468                                         this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
2469                                         Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
2470                                         return false;
2471                                 }
2472                                 // Begin the sync here. this kickstarts the
2473                                 // other side, waiting in WAIT_AUTH_2 state,
2474                                 // into starting their burst, as it shows
2475                                 // that we're happy.
2476                                 this->LinkState = CONNECTED;
2477                                 // we should add the details of this server now
2478                                 // to the servers tree, as a child of the root
2479                                 // node.
2480                                 TreeServer* Node = new TreeServer(sname,description,TreeRoot,this);
2481                                 TreeRoot->AddChild(Node);
2482                                 params[3] = ":" + params[3];
2483                                 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,sname);
2484                                 this->bursting = true;
2485                                 this->DoBurst(Node);
2486                                 return true;
2487                         }
2488                 }
2489                 this->WriteLine("ERROR :Invalid credentials");
2490                 Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, invalid link credentials");
2491                 return false;
2492         }
2493
2494         bool Inbound_Server(std::deque<std::string> &params)
2495         {
2496                 if (params.size() < 4)
2497                         return false;
2498
2499                 irc::string servername = params[0].c_str();
2500                 std::string sname = params[0];
2501                 std::string password = params[1];
2502                 int hops = atoi(params[2].c_str());
2503
2504                 if (hops)
2505                 {
2506                         this->WriteLine("ERROR :Server too far away for authentication");
2507                         Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2508                         return false;
2509                 }
2510                 std::string description = params[3];
2511                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2512                 {
2513                         if ((x->Name == servername) && (x->RecvPass == password))
2514                         {
2515                                 TreeServer* CheckDupe = FindServer(sname);
2516                                 if (CheckDupe)
2517                                 {
2518                                         this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
2519                                         Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
2520                                         return false;
2521                                 }
2522                                 /* If the config says this link is encrypted, but the remote side
2523                                  * hasnt bothered to send the AES command before SERVER, then we
2524                                  * boot them off as we MUST have this connection encrypted.
2525                                  */
2526                                 if ((x->EncryptionKey != "") && (!this->ctx_in))
2527                                 {
2528                                         this->WriteLine("ERROR :This link requires AES encryption to be enabled. Plaintext connection refused.");
2529                                         Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, remote server did not enable AES.");
2530                                         return false;
2531                                 }
2532                                 Srv->SendOpers("*** Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
2533                                 this->InboundServerName = sname;
2534                                 this->InboundDescription = description;
2535                                 // this is good. Send our details: Our server name and description and hopcount of 0,
2536                                 // along with the sendpass from this block.
2537                                 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
2538                                 // move to the next state, we are now waiting for THEM.
2539                                 this->LinkState = WAIT_AUTH_2;
2540                                 return true;
2541                         }
2542                 }
2543                 this->WriteLine("ERROR :Invalid credentials");
2544                 Srv->SendOpers("*** Server connection from \2"+sname+"\2 denied, invalid link credentials");
2545                 return false;
2546         }
2547
2548         void Split(std::string line, std::deque<std::string> &n)
2549         {
2550                 n.clear();
2551                 irc::tokenstream tokens(line);
2552                 std::string param;
2553                 while ((param = tokens.GetToken()) != "")
2554                         n.push_back(param);
2555                 return;
2556         }
2557
2558         bool ProcessLine(std::string line)
2559         {
2560                 std::deque<std::string> params;
2561                 irc::string command;
2562                 std::string prefix;
2563                 
2564                 if (line.empty())
2565                         return true;
2566                 
2567                 line = line.substr(0, line.find_first_of("\r\n"));
2568                 
2569                 log(DEBUG,"IN: %s", line.c_str());
2570                 
2571                 this->Split(line.c_str(),params);
2572                         
2573                 if ((params[0][0] == ':') && (params.size() > 1))
2574                 {
2575                         prefix = params[0].substr(1);
2576                         params.pop_front();
2577                 }
2578
2579                 command = params[0].c_str();
2580                 params.pop_front();
2581
2582                 if ((!this->ctx_in) && (command == "AES"))
2583                 {
2584                         std::string sserv = params[0];
2585                         for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2586                         {
2587                                 if ((x->EncryptionKey != "") && (x->Name == sserv))
2588                                 {
2589                                         this->InitAES(x->EncryptionKey,sserv);
2590                                 }
2591                         }
2592
2593                         return true;
2594                 }
2595                 else if ((this->ctx_in) && (command == "AES"))
2596                 {
2597                         WriteOpers("*** \2AES\2: Encryption already enabled on this connection yet %s is trying to enable it twice!",params[0].c_str());
2598                 }
2599
2600                 switch (this->LinkState)
2601                 {
2602                         TreeServer* Node;
2603                         
2604                         case WAIT_AUTH_1:
2605                                 // Waiting for SERVER command from remote server. Server initiating
2606                                 // the connection sends the first SERVER command, listening server
2607                                 // replies with theirs if its happy, then if the initiator is happy,
2608                                 // it starts to send its net sync, which starts the merge, otherwise
2609                                 // it sends an ERROR.
2610                                 if (command == "PASS")
2611                                 {
2612                                         /* Silently ignored */
2613                                 }
2614                                 else if (command == "SERVER")
2615                                 {
2616                                         return this->Inbound_Server(params);
2617                                 }
2618                                 else if (command == "ERROR")
2619                                 {
2620                                         return this->Error(params);
2621                                 }
2622                                 else if (command == "USER")
2623                                 {
2624                                         this->WriteLine("ERROR :Client connections to this port are prohibited.");
2625                                         return false;
2626                                 }
2627                                 else if (command == "CAPAB")
2628                                 {
2629                                         return this->Capab(params);
2630                                 }
2631                                 else if ((command == "U") || (command == "S"))
2632                                 {
2633                                         this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
2634                                         return false;
2635                                 }
2636                                 else
2637                                 {
2638                                         this->WriteLine("ERROR :Invalid command in negotiation phase.");
2639                                         return false;
2640                                 }
2641                         break;
2642                         case WAIT_AUTH_2:
2643                                 // Waiting for start of other side's netmerge to say they liked our
2644                                 // password.
2645                                 if (command == "SERVER")
2646                                 {
2647                                         // cant do this, they sent it to us in the WAIT_AUTH_1 state!
2648                                         // silently ignore.
2649                                         return true;
2650                                 }
2651                                 else if ((command == "U") || (command == "S"))
2652                                 {
2653                                         this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
2654                                         return false;
2655                                 }
2656                                 else if (command == "BURST")
2657                                 {
2658                                         if (params.size())
2659                                         {
2660                                                 /* If a time stamp is provided, try and check syncronization */
2661                                                 time_t THEM = atoi(params[0].c_str());
2662                                                 long delta = THEM-time(NULL);
2663                                                 if ((delta < -600) || (delta > 600))
2664                                                 {
2665                                                         WriteOpers("*** \2ERROR\2: Your clocks are out by %d seconds (this is more than ten minutes). Link aborted, \2PLEASE SYNC YOUR CLOCKS!\2",abs(delta));
2666                                                         this->WriteLine("ERROR :Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than ten minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
2667                                                         return false;
2668                                                 }
2669                                                 else if ((delta < -60) || (delta > 60))
2670                                                 {
2671                                                         WriteOpers("*** \2WARNING\2: Your clocks are out by %d seconds, please consider synching your clocks.",abs(delta));
2672                                                 }
2673                                         }
2674                                         this->LinkState = CONNECTED;
2675                                         Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
2676                                         TreeRoot->AddChild(Node);
2677                                         params.clear();
2678                                         params.push_back(InboundServerName);
2679                                         params.push_back("*");
2680                                         params.push_back("1");
2681                                         params.push_back(":"+InboundDescription);
2682                                         DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
2683                                         this->bursting = true;
2684                                         this->DoBurst(Node);
2685                                 }
2686                                 else if (command == "ERROR")
2687                                 {
2688                                         return this->Error(params);
2689                                 }
2690                                 else if (command == "CAPAB")
2691                                 {
2692                                         return this->Capab(params);
2693                                 }
2694                                 
2695                         break;
2696                         case LISTENER:
2697                                 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
2698                                 return false;
2699                         break;
2700                         case CONNECTING:
2701                                 if (command == "SERVER")
2702                                 {
2703                                         // another server we connected to, which was in WAIT_AUTH_1 state,
2704                                         // has just sent us their credentials. If we get this far, theyre
2705                                         // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
2706                                         // if we're happy with this, we should send our netburst which
2707                                         // kickstarts the merge.
2708                                         return this->Outbound_Reply_Server(params);
2709                                 }
2710                                 else if (command == "ERROR")
2711                                 {
2712                                         return this->Error(params);
2713                                 }
2714                         break;
2715                         case CONNECTED:
2716                                 // This is the 'authenticated' state, when all passwords
2717                                 // have been exchanged and anything past this point is taken
2718                                 // as gospel.
2719                                 
2720                                 if (prefix != "")
2721                                 {
2722                                         std::string direction = prefix;
2723                                         userrec* t = Srv->FindNick(prefix);
2724                                         if (t)
2725                                         {
2726                                                 direction = t->server;
2727                                         }
2728                                         TreeServer* route_back_again = BestRouteTo(direction);
2729                                         if ((!route_back_again) || (route_back_again->GetSocket() != this))
2730                                         {
2731                                                 if (route_back_again)
2732                                                         log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
2733                                                 return true;
2734                                         }
2735
2736                                         /* Fix by brain:
2737                                          * When there is activity on the socket, reset the ping counter so
2738                                          * that we're not wasting bandwidth pinging an active server.
2739                                          */ 
2740                                         route_back_again->SetNextPingTime(time(NULL) + 120);
2741                                         route_back_again->SetPingFlag();
2742                                 }
2743                                 
2744                                 if (command == "SVSMODE")
2745                                 {
2746                                         /* Services expects us to implement
2747                                          * SVSMODE. In inspircd its the same as
2748                                          * MODE anyway.
2749                                          */
2750                                         command = "MODE";
2751                                 }
2752                                 std::string target = "";
2753                                 /* Yes, know, this is a mess. Its reasonably fast though as we're
2754                                  * working with std::string here.
2755                                  */
2756                                 if ((command == "NICK") && (params.size() > 1))
2757                                 {
2758                                         return this->IntroduceClient(prefix,params);
2759                                 }
2760                                 else if (command == "FJOIN")
2761                                 {
2762                                         return this->ForceJoin(prefix,params);
2763                                 }
2764                                 else if (command == "STATS")
2765                                 {
2766                                         return this->Stats(prefix, params);
2767                                 }
2768                                 else if (command == "SERVER")
2769                                 {
2770                                         return this->RemoteServer(prefix,params);
2771                                 }
2772                                 else if (command == "ERROR")
2773                                 {
2774                                         return this->Error(params);
2775                                 }
2776                                 else if (command == "OPERTYPE")
2777                                 {
2778                                         return this->OperType(prefix,params);
2779                                 }
2780                                 else if (command == "FMODE")
2781                                 {
2782                                         return this->ForceMode(prefix,params);
2783                                 }
2784                                 else if (command == "KILL")
2785                                 {
2786                                         return this->RemoteKill(prefix,params);
2787                                 }
2788                                 else if (command == "FTOPIC")
2789                                 {
2790                                         return this->ForceTopic(prefix,params);
2791                                 }
2792                                 else if (command == "REHASH")
2793                                 {
2794                                         return this->RemoteRehash(prefix,params);
2795                                 }
2796                                 else if (command == "METADATA")
2797                                 {
2798                                         return this->MetaData(prefix,params);
2799                                 }
2800                                 else if (command == "PING")
2801                                 {
2802                                         /*
2803                                          * We just got a ping from a server that's bursting.
2804                                          * This can't be right, so set them to not bursting, and
2805                                          * apply their lines.
2806                                          */
2807                                         if (this->bursting)
2808                                         {
2809                                                 this->bursting = false;
2810                                                 apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2811                                         }
2812                                         if (prefix == "")
2813                                         {
2814                                                 prefix = this->GetName();
2815                                         }
2816                                         return this->LocalPing(prefix,params);
2817                                 }
2818                                 else if (command == "PONG")
2819                                 {
2820                                         /*
2821                                          * We just got a pong from a server that's bursting.
2822                                          * This can't be right, so set them to not bursting, and
2823                                          * apply their lines.
2824                                          */
2825                                         if (this->bursting)
2826                                         {
2827                                                 this->bursting = false;
2828                                                 apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2829                                         }
2830                                         if (prefix == "")
2831                                         {
2832                                                 prefix = this->GetName();
2833                                         }
2834                                         return this->LocalPong(prefix,params);
2835                                 }
2836                                 else if (command == "VERSION")
2837                                 {
2838                                         return this->ServerVersion(prefix,params);
2839                                 }
2840                                 else if (command == "FHOST")
2841                                 {
2842                                         return this->ChangeHost(prefix,params);
2843                                 }
2844                                 else if (command == "FNAME")
2845                                 {
2846                                         return this->ChangeName(prefix,params);
2847                                 }
2848                                 else if (command == "ADDLINE")
2849                                 {
2850                                         return this->AddLine(prefix,params);
2851                                 }
2852                                 else if (command == "SVSNICK")
2853                                 {
2854                                         if (prefix == "")
2855                                         {
2856                                                 prefix = this->GetName();
2857                                         }
2858                                         return this->ForceNick(prefix,params);
2859                                 }
2860                                 else if (command == "IDLE")
2861                                 {
2862                                         return this->Whois(prefix,params);
2863                                 }
2864                                 else if (command == "PUSH")
2865                                 {
2866                                         return this->Push(prefix,params);
2867                                 }
2868                                 else if (command == "TIME")
2869                                 {
2870                                         return this->Time(prefix,params);
2871                                 }
2872                                 else if ((command == "KICK") && (IsServer(prefix)))
2873                                 {
2874                                         std::string sourceserv = this->myhost;
2875                                         if (params.size() == 3)
2876                                         {
2877                                                 userrec* user = Srv->FindNick(params[1]);
2878                                                 chanrec* chan = Srv->FindChannel(params[0]);
2879                                                 if (user && chan)
2880                                                 {
2881                                                         server_kick_channel(user,chan,(char*)params[2].c_str(),false);
2882                                                 }
2883                                         }
2884                                         if (this->InboundServerName != "")
2885                                         {
2886                                                 sourceserv = this->InboundServerName;
2887                                         }
2888                                         return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
2889                                 }
2890                                 else if (command == "SVSJOIN")
2891                                 {
2892                                         if (prefix == "")
2893                                         {
2894                                                 prefix = this->GetName();
2895                                         }
2896                                         return this->ServiceJoin(prefix,params);
2897                                 }
2898                                 else if (command == "SQUIT")
2899                                 {
2900                                         if (params.size() == 2)
2901                                         {
2902                                                 this->Squit(FindServer(params[0]),params[1]);
2903                                         }
2904                                         return true;
2905                                 }
2906                                 else if (command == "ENDBURST")
2907                                 {
2908                                         this->bursting = false;
2909                                         apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2910                                         std::string sourceserv = this->myhost;
2911                                         if (this->InboundServerName != "")
2912                                         {
2913                                                 sourceserv = this->InboundServerName;
2914                                         }
2915                                         WriteOpers("*** Received end of netburst from \2%s\2",sourceserv.c_str());
2916                                         return true;
2917                                 }
2918                                 else
2919                                 {
2920                                         // not a special inter-server command.
2921                                         // Emulate the actual user doing the command,
2922                                         // this saves us having a huge ugly parser.
2923                                         userrec* who = Srv->FindNick(prefix);
2924                                         std::string sourceserv = this->myhost;
2925                                         if (this->InboundServerName != "")
2926                                         {
2927                                                 sourceserv = this->InboundServerName;
2928                                         }
2929                                         if (who)
2930                                         {
2931                                                 if ((command == "NICK") && (params.size() > 0))
2932                                                 {
2933                                                         /* On nick messages, check that the nick doesnt
2934                                                          * already exist here. If it does, kill their copy,
2935                                                          * and our copy.
2936                                                          */
2937                                                         userrec* x = Srv->FindNick(params[0]);
2938                                                         if ((x) && (x != who))
2939                                                         {
2940                                                                 std::deque<std::string> p;
2941                                                                 p.push_back(params[0]);
2942                                                                 p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
2943                                                                 DoOneToMany(Srv->GetServerName(),"KILL",p);
2944                                                                 p.clear();
2945                                                                 p.push_back(prefix);
2946                                                                 p.push_back("Nickname collision");
2947                                                                 DoOneToMany(Srv->GetServerName(),"KILL",p);
2948                                                                 Srv->QuitUser(x,"Nickname collision ("+prefix+" -> "+params[0]+")");
2949                                                                 userrec* y = Srv->FindNick(prefix);
2950                                                                 if (y)
2951                                                                 {
2952                                                                         Srv->QuitUser(y,"Nickname collision");
2953                                                                 }
2954                                                                 return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
2955                                                         }
2956                                                 }
2957                                                 // its a user
2958                                                 target = who->server;
2959                                                 const char* strparams[127];
2960                                                 for (unsigned int q = 0; q < params.size(); q++)
2961                                                 {
2962                                                         strparams[q] = params[q].c_str();
2963                                                 }
2964                                                 if (!Srv->CallCommandHandler(command.c_str(), strparams, params.size(), who))
2965                                                 {
2966                                                         this->WriteLine("ERROR :Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
2967                                                         return false;
2968                                                 }
2969                                         }
2970                                         else
2971                                         {
2972                                                 // its not a user. Its either a server, or somethings screwed up.
2973                                                 if (IsServer(prefix))
2974                                                 {
2975                                                         target = Srv->GetServerName();
2976                                                 }
2977                                                 else
2978                                                 {
2979                                                         log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
2980                                                         return true;
2981                                                 }
2982                                         }
2983                                         return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
2984
2985                                 }
2986                                 return true;
2987                         break;
2988                 }
2989                 return true;
2990         }
2991
2992         virtual std::string GetName()
2993         {
2994                 std::string sourceserv = this->myhost;
2995                 if (this->InboundServerName != "")
2996                 {
2997                         sourceserv = this->InboundServerName;
2998                 }
2999                 return sourceserv;
3000         }
3001
3002         virtual void OnTimeout()
3003         {
3004                 if (this->LinkState == CONNECTING)
3005                 {
3006                         Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
3007                 }
3008         }
3009
3010         virtual void OnClose()
3011         {
3012                 // Connection closed.
3013                 // If the connection is fully up (state CONNECTED)
3014                 // then propogate a netsplit to all peers.
3015                 std::string quitserver = this->myhost;
3016                 if (this->InboundServerName != "")
3017                 {
3018                         quitserver = this->InboundServerName;
3019                 }
3020                 TreeServer* s = FindServer(quitserver);
3021                 if (s)
3022                 {
3023                         Squit(s,"Remote host closed the connection");
3024                 }
3025                 WriteOpers("Server '\2%s\2' closed the connection.",quitserver.c_str());
3026         }
3027
3028         virtual int OnIncomingConnection(int newsock, char* ip)
3029         {
3030                 /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
3031                  * or discovering if this port is the server port, we don't allow connections from any
3032                  * IPs for which we don't have a link block.
3033                  */
3034                 bool found = false;
3035                 char resolved_host[MAXBUF];
3036                 vector<Link>::iterator i;
3037                 for (i = LinkBlocks.begin(); i != LinkBlocks.end(); i++)
3038                 {
3039                         if (i->IPAddr == ip)
3040                         {
3041                                 found = true;
3042                                 break;
3043                         }
3044                         /* XXX: Fixme: blocks for a very short amount of time,
3045                          * we should cache these on rehash/startup
3046                          */
3047                         if (CleanAndResolve(resolved_host,i->IPAddr.c_str(),true,1))
3048                         {
3049                                 if (std::string(resolved_host) == ip)
3050                                 {
3051                                         found = true;
3052                                         break;
3053                                 }
3054                         }
3055                 }
3056                 if (!found)
3057                 {
3058                         WriteOpers("Server connection from %s denied (no link blocks with that IP address)", ip);
3059                         close(newsock);
3060                         return false;
3061                 }
3062                 TreeSocket* s = new TreeSocket(newsock, ip);
3063                 Srv->AddSocket(s);
3064                 return true;
3065         }
3066 };
3067
3068 /** This class is used to resolve server hostnames during /connect and autoconnect.
3069  * As of 1.1, the resolver system is seperated out from InspSocket, so we must do this
3070  * resolver step first ourselves if we need it. This is totally nonblocking, and will
3071  * callback to OnLookupComplete or OnError when completed. Once it has completed we
3072  * will have an IP address which we can then use to continue our connection.
3073  */
3074 class ServernameResolver : public Resolver
3075 {       
3076  private:
3077         /** A copy of the Link tag info for what we're connecting to.
3078          * We take a copy, rather than using a pointer, just in case the
3079          * admin takes the tag away and rehashes while the domain is resolving.
3080          */
3081         Link MyLink;
3082  public:        
3083         ServernameResolver(const std::string &hostname, Link x) : Resolver(hostname, true), MyLink(x)
3084         {
3085                 /* Nothing in here, folks */
3086         }
3087         
3088         void OnLookupComplete(const std::string &result)
3089         {
3090                 /* Initiate the connection, now that we have an IP to use.
3091                  * Passing a hostname directly to InspSocket causes it to
3092                  * just bail and set its FD to -1.
3093                  */
3094                 TreeServer* CheckDupe = FindServer(MyLink.Name.c_str());
3095                 if (!CheckDupe) /* Check that nobody tried to connect it successfully while we were resolving */
3096                 {
3097                         TreeSocket* newsocket = new TreeSocket(result,MyLink.Port,false,10,MyLink.Name.c_str());
3098                         if (newsocket->GetFd() > -1)
3099                         {
3100                                 /* We're all OK */
3101                                 Srv->AddSocket(newsocket);
3102                         }
3103                         else
3104                         {
3105                                 /* Something barfed, show the opers */
3106                                 WriteOpers("*** CONNECT: Error connecting \002%s\002: %s.",MyLink.Name.c_str(),strerror(errno));
3107                                 delete newsocket;
3108                         }
3109                 }
3110         }
3111
3112         void OnError(ResolverError e)
3113         {
3114                 /* Ooops! */
3115                 WriteOpers("*** CONNECT: Error connecting \002%s\002: Unable to resolve hostname.",MyLink.Name.c_str());
3116         }
3117 };
3118
3119
3120 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
3121 {
3122         for (unsigned int c = 0; c < list.size(); c++)
3123         {
3124                 if (list[c] == server)
3125                 {
3126                         return;
3127                 }
3128         }
3129         list.push_back(server);
3130 }
3131
3132 // returns a list of DIRECT servernames for a specific channel
3133 void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
3134 {
3135         CUList *ulist = c->GetUsers();
3136         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
3137         {
3138                 if (i->second->fd < 0)
3139                 {
3140                         TreeServer* best = BestRouteTo(i->second->server);
3141                         if (best)
3142                                 AddThisServer(best,list);
3143                 }
3144         }
3145         return;
3146 }
3147
3148 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, irc::string command, std::deque<std::string> &params)
3149 {
3150         TreeServer* omitroute = BestRouteTo(omit);
3151         if ((command == "NOTICE") || (command == "PRIVMSG"))
3152         {
3153                 if (params.size() >= 2)
3154                 {
3155                         /* Prefixes */
3156                         if ((*(params[0].c_str()) == '@') || (*(params[0].c_str()) == '%') || (*(params[0].c_str()) == '+'))
3157                         {
3158                                 params[0] = params[0].substr(1, params[0].length()-1);
3159                         }
3160                         if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$'))
3161                         {
3162                                 // special routing for private messages/notices
3163                                 userrec* d = Srv->FindNick(params[0]);
3164                                 if (d)
3165                                 {
3166                                         std::deque<std::string> par;
3167                                         par.push_back(params[0]);
3168                                         par.push_back(":"+params[1]);
3169                                         DoOneToOne(prefix,command.c_str(),par,d->server);
3170                                         return true;
3171                                 }
3172                         }
3173                         else if (*(params[0].c_str()) == '$')
3174                         {
3175                                 std::deque<std::string> par;
3176                                 par.push_back(params[0]);
3177                                 par.push_back(":"+params[1]);
3178                                 DoOneToAllButSender(prefix,command.c_str(),par,omitroute->GetName());
3179                                 return true;
3180                         }
3181                         else
3182                         {
3183                                 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
3184                                 chanrec* c = Srv->FindChannel(params[0]);
3185                                 if (c)
3186                                 {
3187                                         std::deque<TreeServer*> list;
3188                                         GetListOfServersForChannel(c,list);
3189                                         log(DEBUG,"Got a list of %d servers",list.size());
3190                                         unsigned int lsize = list.size();
3191                                         for (unsigned int i = 0; i < lsize; i++)
3192                                         {
3193                                                 TreeSocket* Sock = list[i]->GetSocket();
3194                                                 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
3195                                                 {
3196                                                         log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
3197                                                         Sock->WriteLine(data);
3198                                                 }
3199                                         }
3200                                         return true;
3201                                 }
3202                         }
3203                 }
3204         }
3205         unsigned int items = TreeRoot->ChildCount();
3206         for (unsigned int x = 0; x < items; x++)
3207         {
3208                 TreeServer* Route = TreeRoot->GetChild(x);
3209                 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3210                 {
3211                         TreeSocket* Sock = Route->GetSocket();
3212                         Sock->WriteLine(data);
3213                 }
3214         }
3215         return true;
3216 }
3217
3218 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> &params, std::string omit)
3219 {
3220         TreeServer* omitroute = BestRouteTo(omit);
3221         std::string FullLine = ":" + prefix + " " + command;
3222         unsigned int words = params.size();
3223         for (unsigned int x = 0; x < words; x++)
3224         {
3225                 FullLine = FullLine + " " + params[x];
3226         }
3227         unsigned int items = TreeRoot->ChildCount();
3228         for (unsigned int x = 0; x < items; x++)
3229         {
3230                 TreeServer* Route = TreeRoot->GetChild(x);
3231                 // Send the line IF:
3232                 // The route has a socket (its a direct connection)
3233                 // The route isnt the one to be omitted
3234                 // The route isnt the path to the one to be omitted
3235                 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3236                 {
3237                         TreeSocket* Sock = Route->GetSocket();
3238                         Sock->WriteLine(FullLine);
3239                 }
3240         }
3241         return true;
3242 }
3243
3244 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> &params)
3245 {
3246         std::string FullLine = ":" + prefix + " " + command;
3247         unsigned int words = params.size();
3248         for (unsigned int x = 0; x < words; x++)
3249         {
3250                 FullLine = FullLine + " " + params[x];
3251         }
3252         unsigned int items = TreeRoot->ChildCount();
3253         for (unsigned int x = 0; x < items; x++)
3254         {
3255                 TreeServer* Route = TreeRoot->GetChild(x);
3256                 if (Route->GetSocket())
3257                 {
3258                         TreeSocket* Sock = Route->GetSocket();
3259                         Sock->WriteLine(FullLine);
3260                 }
3261         }
3262         return true;
3263 }
3264
3265 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> &params, std::string target)
3266 {
3267         TreeServer* Route = BestRouteTo(target);
3268         if (Route)
3269         {
3270                 std::string FullLine = ":" + prefix + " " + command;
3271                 unsigned int words = params.size();
3272                 for (unsigned int x = 0; x < words; x++)
3273                 {
3274                         FullLine = FullLine + " " + params[x];
3275                 }
3276                 if (Route->GetSocket())
3277                 {
3278                         TreeSocket* Sock = Route->GetSocket();
3279                         Sock->WriteLine(FullLine);
3280                 }
3281                 return true;
3282         }
3283         else
3284         {
3285                 return true;
3286         }
3287 }
3288
3289 std::vector<TreeSocket*> Bindings;
3290
3291 void ReadConfiguration(bool rebind)
3292 {
3293         Conf = new ConfigReader;
3294         if (rebind)
3295         {
3296                 for (int j =0; j < Conf->Enumerate("bind"); j++)
3297                 {
3298                         std::string Type = Conf->ReadValue("bind","type",j);
3299                         std::string IP = Conf->ReadValue("bind","address",j);
3300                         long Port = Conf->ReadInteger("bind","port",j,true);
3301                         if (Type == "servers")
3302                         {
3303                                 if (IP == "*")
3304                                 {
3305                                         IP = "";
3306                                 }
3307                                 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
3308                                 if (listener->GetState() == I_LISTENING)
3309                                 {
3310                                         Srv->AddSocket(listener);
3311                                         Bindings.push_back(listener);
3312                                 }
3313                                 else
3314                                 {
3315                                         log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
3316                                         listener->Close();
3317                                         DELETE(listener);
3318                                 }
3319                         }
3320                 }
3321         }
3322         FlatLinks = Conf->ReadFlag("options","flatlinks",0);
3323         HideULines = Conf->ReadFlag("options","hideulines",0);
3324         LinkBlocks.clear();
3325         for (int j =0; j < Conf->Enumerate("link"); j++)
3326         {
3327                 Link L;
3328                 L.Name = (Conf->ReadValue("link","name",j)).c_str();
3329                 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
3330                 L.Port = Conf->ReadInteger("link","port",j,true);
3331                 L.SendPass = Conf->ReadValue("link","sendpass",j);
3332                 L.RecvPass = Conf->ReadValue("link","recvpass",j);
3333                 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
3334                 L.EncryptionKey =  Conf->ReadValue("link","encryptionkey",j);
3335                 L.HiddenFromStats = Conf->ReadFlag("link","hidden",j);
3336                 L.NextConnectTime = time(NULL) + L.AutoConnect;
3337                 /* Bugfix by brain, do not allow people to enter bad configurations */
3338                 if ((L.IPAddr != "") && (L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
3339                 {
3340                         LinkBlocks.push_back(L);
3341                         log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
3342                 }
3343                 else
3344                 {
3345                         if (L.IPAddr == "")
3346                         {
3347                                 log(DEFAULT,"Invalid configuration for server '%s', IP address not defined!",L.Name.c_str());
3348                         }
3349                         else if (L.RecvPass == "")
3350                         {
3351                                 log(DEFAULT,"Invalid configuration for server '%s', recvpass not defined!",L.Name.c_str());
3352                         }
3353                         else if (L.SendPass == "")
3354                         {
3355                                 log(DEFAULT,"Invalid configuration for server '%s', sendpass not defined!",L.Name.c_str());
3356                         }
3357                         else if (L.Name == "")
3358                         {
3359                                 log(DEFAULT,"Invalid configuration, link tag without a name!");
3360                         }
3361                         else if (!L.Port)
3362                         {
3363                                 log(DEFAULT,"Invalid configuration for server '%s', no port specified!",L.Name.c_str());
3364                         }
3365                 }
3366         }
3367         DELETE(Conf);
3368 }
3369
3370
3371 class ModuleSpanningTree : public Module
3372 {
3373         std::vector<TreeSocket*> Bindings;
3374         int line;
3375         int NumServers;
3376         unsigned int max_local;
3377         unsigned int max_global;
3378         cmd_rconnect* command_rconnect;
3379
3380  public:
3381
3382         ModuleSpanningTree(Server* Me)
3383                 : Module::Module(Me), max_local(0), max_global(0)
3384         {
3385                 Srv = Me;
3386                 Bindings.clear();
3387
3388                 // Create the root of the tree
3389                 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
3390
3391                 ReadConfiguration(true);
3392
3393                 command_rconnect = new cmd_rconnect(this);
3394                 Srv->AddCommand(command_rconnect);
3395         }
3396
3397         void ShowLinks(TreeServer* Current, userrec* user, int hops)
3398         {
3399                 std::string Parent = TreeRoot->GetName();
3400                 if (Current->GetParent())
3401                 {
3402                         Parent = Current->GetParent()->GetName();
3403                 }
3404                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
3405                 {
3406                         if ((HideULines) && (Srv->IsUlined(Current->GetChild(q)->GetName())))
3407                         {
3408                                 if (*user->oper)
3409                                 {
3410                                          ShowLinks(Current->GetChild(q),user,hops+1);
3411                                 }
3412                         }
3413                         else
3414                         {
3415                                 ShowLinks(Current->GetChild(q),user,hops+1);
3416                         }
3417                 }
3418                 /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
3419                 if ((HideULines) && (Srv->IsUlined(Current->GetName())) && (!*user->oper))
3420                         return;
3421                 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),(FlatLinks && (!*user->oper)) ? Srv->GetServerName().c_str() : Parent.c_str(),(FlatLinks && (!*user->oper)) ? 0 : hops,Current->GetDesc().c_str());
3422         }
3423
3424         int CountLocalServs()
3425         {
3426                 return TreeRoot->ChildCount();
3427         }
3428
3429         int CountServs()
3430         {
3431                 return serverlist.size();
3432         }
3433
3434         void HandleLinks(const char** parameters, int pcnt, userrec* user)
3435         {
3436                 ShowLinks(TreeRoot,user,0);
3437                 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
3438                 return;
3439         }
3440
3441         void HandleLusers(const char** parameters, int pcnt, userrec* user)
3442         {
3443                 unsigned int n_users = usercnt();
3444
3445                 /* Only update these when someone wants to see them, more efficient */
3446                 if ((unsigned int)local_count() > max_local)
3447                         max_local = local_count();
3448                 if (n_users > max_global)
3449                         max_global = n_users;
3450
3451                 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,n_users-usercount_invisible(),usercount_invisible(),this->CountServs());
3452                 if (usercount_opers())
3453                         WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
3454                 if (usercount_unknown())
3455                         WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
3456                 if (chancount())
3457                         WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
3458                 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
3459                 WriteServ(user->fd,"265 %s :Current Local Users: %d  Max: %d",user->nick,local_count(),max_local);
3460                 WriteServ(user->fd,"266 %s :Current Global Users: %d  Max: %d",user->nick,n_users,max_global);
3461                 return;
3462         }
3463
3464         // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
3465
3466         void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80], float &totusers, float &totservers)
3467         {
3468                 if (line < 128)
3469                 {
3470                         for (int t = 0; t < depth; t++)
3471                         {
3472                                 matrix[line][t] = ' ';
3473                         }
3474
3475                         // For Aligning, we need to work out exactly how deep this thing is, and produce
3476                         // a 'Spacer' String to compensate.
3477                         char spacer[40];
3478
3479                         memset(spacer,' ',40);
3480                         if ((40 - Current->GetName().length() - depth) > 1) {
3481                                 spacer[40 - Current->GetName().length() - depth] = '\0';
3482                         }
3483                         else
3484                         {
3485                                 spacer[5] = '\0';
3486                         }
3487
3488                         float percent;
3489                         char text[80];
3490                         if (clientlist.size() == 0) {
3491                                 // If there are no users, WHO THE HELL DID THE /MAP?!?!?!
3492                                 percent = 0;
3493                         }
3494                         else
3495                         {
3496                                 percent = ((float)Current->GetUserCount() / (float)clientlist.size()) * 100;
3497                         }
3498                         snprintf(text, 80, "%s %s%5d [%5.2f%%]", Current->GetName().c_str(), spacer, Current->GetUserCount(), percent);
3499                         totusers += Current->GetUserCount();
3500                         totservers++;
3501                         strlcpy(&matrix[line][depth],text,80);
3502                         line++;
3503                         for (unsigned int q = 0; q < Current->ChildCount(); q++)
3504                         {
3505                                 if ((HideULines) && (Srv->IsUlined(Current->GetChild(q)->GetName())))
3506                                 {
3507                                         if (*user->oper)
3508                                         {
3509                                                 ShowMap(Current->GetChild(q),user,(FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
3510                                         }
3511                                 }
3512                                 else
3513                                 {
3514                                         ShowMap(Current->GetChild(q),user,(FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
3515                                 }
3516                         }
3517                 }
3518         }
3519
3520         int HandleStats(const char** parameters, int pcnt, userrec* user)
3521         {
3522                 if (pcnt > 1)
3523                 {
3524                         /* Remote STATS, the server is within the 2nd parameter */
3525                         std::deque<std::string> params;
3526                         params.push_back(parameters[0]);
3527                         params.push_back(parameters[1]);
3528                         /* Send it out remotely, generate no reply yet */
3529                         TreeServer* s = FindServerMask(parameters[1]);
3530                         if (s)
3531                         {
3532                                 params[1] = s->GetName();
3533                                 DoOneToOne(user->nick, "STATS", params, s->GetName());
3534                         }
3535                         return 1;
3536                 }
3537                 return 0;
3538         }
3539
3540         // Ok, prepare to be confused.
3541         // After much mulling over how to approach this, it struck me that
3542         // the 'usual' way of doing a /MAP isnt the best way. Instead of
3543         // keeping track of a ton of ascii characters, and line by line
3544         // under recursion working out where to place them using multiplications
3545         // and divisons, we instead render the map onto a backplane of characters
3546         // (a character matrix), then draw the branches as a series of "L" shapes
3547         // from the nodes. This is not only friendlier on CPU it uses less stack.
3548
3549         void HandleMap(const char** parameters, int pcnt, userrec* user)
3550         {
3551                 // This array represents a virtual screen which we will
3552                 // "scratch" draw to, as the console device of an irc
3553                 // client does not provide for a proper terminal.
3554                 float totusers = 0;
3555                 float totservers = 0;
3556                 char matrix[128][80];
3557                 for (unsigned int t = 0; t < 128; t++)
3558                 {
3559                         matrix[t][0] = '\0';
3560                 }
3561                 line = 0;
3562                 // The only recursive bit is called here.
3563                 ShowMap(TreeRoot,user,0,matrix,totusers,totservers);
3564                 // Process each line one by one. The algorithm has a limit of
3565                 // 128 servers (which is far more than a spanning tree should have
3566                 // anyway, so we're ok). This limit can be raised simply by making
3567                 // the character matrix deeper, 128 rows taking 10k of memory.
3568                 for (int l = 1; l < line; l++)
3569                 {
3570                         // scan across the line looking for the start of the
3571                         // servername (the recursive part of the algorithm has placed
3572                         // the servers at indented positions depending on what they
3573                         // are related to)
3574                         int first_nonspace = 0;
3575                         while (matrix[l][first_nonspace] == ' ')
3576                         {
3577                                 first_nonspace++;
3578                         }
3579                         first_nonspace--;
3580                         // Draw the `- (corner) section: this may be overwritten by
3581                         // another L shape passing along the same vertical pane, becoming
3582                         // a |- (branch) section instead.
3583                         matrix[l][first_nonspace] = '-';
3584                         matrix[l][first_nonspace-1] = '`';
3585                         int l2 = l - 1;
3586                         // Draw upwards until we hit the parent server, causing possibly
3587                         // other corners (`-) to become branches (|-)
3588                         while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
3589                         {
3590                                 matrix[l2][first_nonspace-1] = '|';
3591                                 l2--;
3592                         }
3593                 }
3594                 // dump the whole lot to the user. This is the easy bit, honest.
3595                 for (int t = 0; t < line; t++)
3596                 {
3597                         WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
3598                 }
3599                 float avg_users = totusers / totservers;
3600                 WriteServ(user->fd,"270 %s :%.0f server%s and %.0f user%s, average %.2f users per server",user->nick,totservers,(totservers > 1 ? "s" : ""),totusers,(totusers > 1 ? "s" : ""),avg_users);
3601         WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
3602                 return;
3603         }
3604
3605         int HandleSquit(const char** parameters, int pcnt, userrec* user)
3606         {
3607                 TreeServer* s = FindServerMask(parameters[0]);
3608                 if (s)
3609                 {
3610                         if (s == TreeRoot)
3611                         {
3612                                  WriteServ(user->fd,"NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
3613                                 return 1;
3614                         }
3615                         TreeSocket* sock = s->GetSocket();
3616                         if (sock)
3617                         {
3618                                 log(DEBUG,"Splitting server %s",s->GetName().c_str());
3619                                 WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
3620                                 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
3621                                 Srv->RemoveSocket(sock);
3622                         }
3623                         else
3624                         {
3625                                 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
3626                         }
3627                 }
3628                 else
3629                 {
3630                          WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
3631                 }
3632                 return 1;
3633         }
3634
3635         int HandleTime(const char** parameters, int pcnt, userrec* user)
3636         {
3637                 if ((IS_LOCAL(user)) && (pcnt))
3638                 {
3639                         TreeServer* found = FindServerMask(parameters[0]);
3640                         if (found)
3641                         {
3642                                 // we dont' override for local server
3643                                 if (found == TreeRoot)
3644                                         return 0;
3645                                 
3646                                 std::deque<std::string> params;
3647                                 params.push_back(found->GetName());
3648                                 params.push_back(user->nick);
3649                                 DoOneToOne(Srv->GetServerName(),"TIME",params,found->GetName());
3650                         }
3651                         else
3652                         {
3653                                 WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
3654                         }
3655                 }
3656                 return 1;
3657         }
3658
3659         int HandleRemoteWhois(const char** parameters, int pcnt, userrec* user)
3660         {
3661                 if ((IS_LOCAL(user)) && (pcnt > 1))
3662                 {
3663                         userrec* remote = Srv->FindNick(parameters[1]);
3664                         if ((remote) && (remote->fd < 0))
3665                         {
3666                                 std::deque<std::string> params;
3667                                 params.push_back(parameters[1]);
3668                                 DoOneToOne(user->nick,"IDLE",params,remote->server);
3669                                 return 1;
3670                         }
3671                         else if (!remote)
3672                         {
3673                                 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
3674                                 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
3675                                 return 1;
3676                         }
3677                 }
3678                 return 0;
3679         }
3680
3681         void DoPingChecks(time_t curtime)
3682         {
3683                 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
3684                 {
3685                         TreeServer* serv = TreeRoot->GetChild(j);
3686                         TreeSocket* sock = serv->GetSocket();
3687                         if (sock)
3688                         {
3689                                 if (curtime >= serv->NextPingTime())
3690                                 {
3691                                         if (serv->AnsweredLastPing())
3692                                         {
3693                                                 sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
3694                                                 serv->SetNextPingTime(curtime + 120);
3695                                         }
3696                                         else
3697                                         {
3698                                                 // they didnt answer, boot them
3699                                                 WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
3700                                                 sock->Squit(serv,"Ping timeout");
3701                                                 Srv->RemoveSocket(sock);
3702                                                 return;
3703                                         }
3704                                 }
3705                         }
3706                 }
3707         }
3708
3709         void AutoConnectServers(time_t curtime)
3710         {
3711                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
3712                 {
3713                         if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
3714                         {
3715                                 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
3716                                 x->NextConnectTime = curtime + x->AutoConnect;
3717                                 TreeServer* CheckDupe = FindServer(x->Name.c_str());
3718                                 if (!CheckDupe)
3719                                 {
3720                                         // an autoconnected server is not connected. Check if its time to connect it
3721                                         WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
3722
3723                                         insp_inaddr binip;
3724
3725                                         /* Do we already have an IP? If so, no need to resolve it. */
3726                                         if (insp_aton(x->IPAddr.c_str(), &binip) > 0)
3727                                         {
3728                                                 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name.c_str());
3729                                                 if (newsocket->GetFd() > -1)
3730                                                 {
3731                                                         Srv->AddSocket(newsocket);
3732                                                 }
3733                                                 else
3734                                                 {
3735                                                         WriteOpers("*** AUTOCONNECT: Error autoconnecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
3736                                                         delete newsocket;
3737                                                 }
3738                                         }
3739                                         else
3740                                         {
3741                                                 ServernameResolver* snr = new ServernameResolver(x->IPAddr, *x);
3742                                                 Srv->AddResolver(snr);
3743                                         }
3744
3745                                 }
3746                         }
3747                 }
3748         }
3749
3750         int HandleVersion(const char** parameters, int pcnt, userrec* user)
3751         {
3752                 // we've already checked if pcnt > 0, so this is safe
3753                 TreeServer* found = FindServerMask(parameters[0]);
3754                 if (found)
3755                 {
3756                         std::string Version = found->GetVersion();
3757                         WriteServ(user->fd,"351 %s :%s",user->nick,Version.c_str());
3758                         if (found == TreeRoot)
3759                         {
3760                                 std::stringstream out(Config->data005);
3761                                 std::string token = "";
3762                                 std::string line5 = "";
3763                                 int token_counter = 0;
3764
3765                                 while (!out.eof())
3766                                 {
3767                                         out >> token;
3768                                         line5 = line5 + token + " ";   
3769                                         token_counter++;
3770
3771                                         if ((token_counter >= 13) || (out.eof() == true))
3772                                         {
3773                                                 WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
3774                                                 line5 = "";
3775                                                 token_counter = 0;
3776                                         }
3777                                 }
3778                         }
3779                 }
3780                 else
3781                 {
3782                         WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
3783                 }
3784                 return 1;
3785         }
3786         
3787         int HandleConnect(const char** parameters, int pcnt, userrec* user)
3788         {
3789                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
3790                 {
3791                         if (Srv->MatchText(x->Name.c_str(),parameters[0]))
3792                         {
3793                                 TreeServer* CheckDupe = FindServer(x->Name.c_str());
3794                                 if (!CheckDupe)
3795                                 {
3796                                         WriteServ(user->fd,"NOTICE %s :*** CONNECT: Connecting to server: \002%s\002 (%s:%d)",user->nick,x->Name.c_str(),(x->HiddenFromStats ? "<hidden>" : x->IPAddr.c_str()),x->Port);
3797                                         insp_inaddr binip;
3798
3799                                         /* Do we already have an IP? If so, no need to resolve it. */
3800                                         if (insp_aton(x->IPAddr.c_str(), &binip) > 0)
3801                                         {
3802                                                 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name.c_str());
3803                                                 if (newsocket->GetFd() > -1)
3804                                                 {
3805                                                         Srv->AddSocket(newsocket);
3806                                                 }
3807                                                 else
3808                                                 {
3809                                                         WriteOpers("*** CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
3810                                                         delete newsocket;
3811                                                 }
3812                                         }
3813                                         else
3814                                         {
3815                                                 ServernameResolver* snr = new ServernameResolver(x->IPAddr, *x);
3816                                                 Srv->AddResolver(snr);
3817                                         }
3818                                         return 1;
3819                                 }
3820                                 else
3821                                 {
3822                                         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());
3823                                         return 1;
3824                                 }
3825                         }
3826                 }
3827                 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
3828                 return 1;
3829         }
3830
3831         virtual int OnStats(char statschar, userrec* user, string_list &results)
3832         {
3833                 if (statschar == 'c')
3834                 {
3835                         for (unsigned int i = 0; i < LinkBlocks.size(); i++)
3836                         {
3837                                 results.push_back(Srv->GetServerName()+" 213 "+user->nick+" C *@"+(LinkBlocks[i].HiddenFromStats ? "<hidden>" : LinkBlocks[i].IPAddr)+" * "+LinkBlocks[i].Name.c_str()+" "+ConvToStr(LinkBlocks[i].Port)+" "+(LinkBlocks[i].EncryptionKey != "" ? 'e' : '-')+(LinkBlocks[i].AutoConnect ? 'a' : '-')+'s');
3838                                 results.push_back(Srv->GetServerName()+" 244 "+user->nick+" H * * "+LinkBlocks[i].Name.c_str());
3839                         }
3840                         results.push_back(Srv->GetServerName()+" 219 "+user->nick+" "+statschar+" :End of /STATS report");
3841                         WriteOpers("*** Notice: %s '%c' requested by %s (%s@%s)",(!strcmp(user->server,Config->ServerName) ? "Stats" : "Remote stats"),statschar,user->nick,user->ident,user->host);
3842                         return 1;
3843                 }
3844                 return 0;
3845         }
3846
3847         virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated)
3848         {
3849                 /* If the command doesnt appear to be valid, we dont want to mess with it. */
3850                 if (!validated)
3851                         return 0;
3852
3853                 if (command == "CONNECT")
3854                 {
3855                         return this->HandleConnect(parameters,pcnt,user);
3856                 }
3857                 else if (command == "STATS")
3858                 {
3859                         return this->HandleStats(parameters,pcnt,user);
3860                 }
3861                 else if (command == "SQUIT")
3862                 {
3863                         return this->HandleSquit(parameters,pcnt,user);
3864                 }
3865                 else if (command == "MAP")
3866                 {
3867                         this->HandleMap(parameters,pcnt,user);
3868                         return 1;
3869                 }
3870                 else if ((command == "TIME") && (pcnt > 0))
3871                 {
3872                         return this->HandleTime(parameters,pcnt,user);
3873                 }
3874                 else if (command == "LUSERS")
3875                 {
3876                         this->HandleLusers(parameters,pcnt,user);
3877                         return 1;
3878                 }
3879                 else if (command == "LINKS")
3880                 {
3881                         this->HandleLinks(parameters,pcnt,user);
3882                         return 1;
3883                 }
3884                 else if (command == "WHOIS")
3885                 {
3886                         if (pcnt > 1)
3887                         {
3888                                 // remote whois
3889                                 return this->HandleRemoteWhois(parameters,pcnt,user);
3890                         }
3891                 }
3892                 else if ((command == "VERSION") && (pcnt > 0))
3893                 {
3894                         this->HandleVersion(parameters,pcnt,user);
3895                         return 1;
3896                 }
3897                 else if (Srv->IsValidModuleCommand(command, pcnt, user))
3898                 {
3899                         // this bit of code cleverly routes all module commands
3900                         // to all remote severs *automatically* so that modules
3901                         // can just handle commands locally, without having
3902                         // to have any special provision in place for remote
3903                         // commands and linking protocols.
3904                         std::deque<std::string> params;
3905                         params.clear();
3906                         for (int j = 0; j < pcnt; j++)
3907                         {
3908                                 if (strchr(parameters[j],' '))
3909                                 {
3910                                         params.push_back(":" + std::string(parameters[j]));
3911                                 }
3912                                 else
3913                                 {
3914                                         params.push_back(std::string(parameters[j]));
3915                                 }
3916                         }
3917                         log(DEBUG,"Globally route '%s'",command.c_str());
3918                         DoOneToMany(user->nick,command,params);
3919                 }
3920                 return 0;
3921         }
3922
3923         virtual void OnGetServerDescription(const std::string &servername,std::string &description)
3924         {
3925                 TreeServer* s = FindServer(servername);
3926                 if (s)
3927                 {
3928                         description = s->GetDesc();
3929                 }
3930         }
3931
3932         virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
3933         {
3934                 if (IS_LOCAL(source))
3935                 {
3936                         std::deque<std::string> params;
3937                         params.push_back(dest->nick);
3938                         params.push_back(channel->name);
3939                         DoOneToMany(source->nick,"INVITE",params);
3940                 }
3941         }
3942
3943         virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, const std::string &topic)
3944         {
3945                 std::deque<std::string> params;
3946                 params.push_back(chan->name);
3947                 params.push_back(":"+topic);
3948                 DoOneToMany(user->nick,"TOPIC",params);
3949         }
3950
3951         virtual void OnWallops(userrec* user, const std::string &text)
3952         {
3953                 if (IS_LOCAL(user))
3954                 {
3955                         std::deque<std::string> params;
3956                         params.push_back(":"+text);
3957                         DoOneToMany(user->nick,"WALLOPS",params);
3958                 }
3959         }
3960
3961         virtual void OnUserNotice(userrec* user, void* dest, int target_type, const std::string &text, char status)
3962         {
3963                 if (target_type == TYPE_USER)
3964                 {
3965                         userrec* d = (userrec*)dest;
3966                         if ((d->fd < 0) && (IS_LOCAL(user)))
3967                         {
3968                                 std::deque<std::string> params;
3969                                 params.clear();
3970                                 params.push_back(d->nick);
3971                                 params.push_back(":"+text);
3972                                 DoOneToOne(user->nick,"NOTICE",params,d->server);
3973                         }
3974                 }
3975                 else if (target_type == TYPE_CHANNEL)
3976                 {
3977                         if (IS_LOCAL(user))
3978                         {
3979                                 chanrec *c = (chanrec*)dest;
3980                                 std::string cname = c->name;
3981                                 if (status)
3982                                         cname = status + cname;
3983                                 std::deque<TreeServer*> list;
3984                                 GetListOfServersForChannel(c,list);
3985                                 unsigned int ucount = list.size();
3986                                 for (unsigned int i = 0; i < ucount; i++)
3987                                 {
3988                                         TreeSocket* Sock = list[i]->GetSocket();
3989                                         if (Sock)
3990                                                 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+cname+" :"+text);
3991                                 }
3992                         }
3993                 }
3994                 else if (target_type == TYPE_SERVER)
3995                 {
3996                         if (IS_LOCAL(user))
3997                         {
3998                                 char* target = (char*)dest;
3999                                 std::deque<std::string> par;
4000                                 par.push_back(target);
4001                                 par.push_back(":"+text);
4002                                 DoOneToMany(user->nick,"NOTICE",par);
4003                         }
4004                 }
4005         }
4006
4007         virtual void OnUserMessage(userrec* user, void* dest, int target_type, const std::string &text, char status)
4008         {
4009                 if (target_type == TYPE_USER)
4010                 {
4011                         // route private messages which are targetted at clients only to the server
4012                         // which needs to receive them
4013                         userrec* d = (userrec*)dest;
4014                         if ((d->fd < 0) && (IS_LOCAL(user)))
4015                         {
4016                                 std::deque<std::string> params;
4017                                 params.clear();
4018                                 params.push_back(d->nick);
4019                                 params.push_back(":"+text);
4020                                 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
4021                         }
4022                 }
4023                 else if (target_type == TYPE_CHANNEL)
4024                 {
4025                         if (IS_LOCAL(user))
4026                         {
4027                                 chanrec *c = (chanrec*)dest;
4028                                 std::string cname = c->name;
4029                                 if (status)
4030                                         cname = status + cname;
4031                                 std::deque<TreeServer*> list;
4032                                 GetListOfServersForChannel(c,list);
4033                                 unsigned int ucount = list.size();
4034                                 for (unsigned int i = 0; i < ucount; i++)
4035                                 {
4036                                         TreeSocket* Sock = list[i]->GetSocket();
4037                                         if (Sock)
4038                                                 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+cname+" :"+text);
4039                                 }
4040                         }
4041                 }
4042                 else if (target_type == TYPE_SERVER)
4043                 {
4044                         if (IS_LOCAL(user))
4045                         {
4046                                 char* target = (char*)dest;
4047                                 std::deque<std::string> par;
4048                                 par.push_back(target);
4049                                 par.push_back(":"+text);
4050                                 DoOneToMany(user->nick,"PRIVMSG",par);
4051                         }
4052                 }
4053         }
4054
4055         virtual void OnBackgroundTimer(time_t curtime)
4056         {
4057                 AutoConnectServers(curtime);
4058                 DoPingChecks(curtime);
4059         }
4060
4061         virtual void OnUserJoin(userrec* user, chanrec* channel)
4062         {
4063                 // Only do this for local users
4064                 if (IS_LOCAL(user))
4065                 {
4066                         std::deque<std::string> params;
4067                         params.clear();
4068                         params.push_back(channel->name);
4069
4070                         if (channel->GetUserCounter() > 1)
4071                         {
4072                                 // not the first in the channel
4073                                 DoOneToMany(user->nick,"JOIN",params);
4074                         }
4075                         else
4076                         {
4077                                 // first in the channel, set up their permissions
4078                                 // and the channel TS with FJOIN.
4079                                 char ts[24];
4080                                 snprintf(ts,24,"%lu",(unsigned long)channel->age);
4081                                 params.clear();
4082                                 params.push_back(channel->name);
4083                                 params.push_back(ts);
4084                                 params.push_back("@"+std::string(user->nick));
4085                                 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
4086                         }
4087                 }
4088         }
4089
4090         virtual void OnChangeHost(userrec* user, const std::string &newhost)
4091         {
4092                 // only occurs for local clients
4093                 if (user->registered != REG_ALL)
4094                         return;
4095                 std::deque<std::string> params;
4096                 params.push_back(newhost);
4097                 DoOneToMany(user->nick,"FHOST",params);
4098         }
4099
4100         virtual void OnChangeName(userrec* user, const std::string &gecos)
4101         {
4102                 // only occurs for local clients
4103                 if (user->registered != REG_ALL)
4104                         return;
4105                 std::deque<std::string> params;
4106                 params.push_back(gecos);
4107                 DoOneToMany(user->nick,"FNAME",params);
4108         }
4109
4110         virtual void OnUserPart(userrec* user, chanrec* channel, const std::string &partmessage)
4111         {
4112                 if (IS_LOCAL(user))
4113                 {
4114                         std::deque<std::string> params;
4115                         params.push_back(channel->name);
4116                         if (partmessage != "")
4117                                 params.push_back(":"+partmessage);
4118                         DoOneToMany(user->nick,"PART",params);
4119                 }
4120         }
4121
4122         virtual void OnUserConnect(userrec* user)
4123         {
4124                 char agestr[MAXBUF];
4125                 if (IS_LOCAL(user))
4126                 {
4127                         std::deque<std::string> params;
4128                         snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
4129                         params.push_back(agestr);
4130                         params.push_back(user->nick);
4131                         params.push_back(user->host);
4132                         params.push_back(user->dhost);
4133                         params.push_back(user->ident);
4134                         params.push_back("+"+std::string(user->FormatModes()));
4135                         params.push_back((char*)insp_ntoa(user->ip4));
4136                         params.push_back(":"+std::string(user->fullname));
4137                         DoOneToMany(Srv->GetServerName(),"NICK",params);
4138
4139                         // User is Local, change needs to be reflected!
4140                         TreeServer* SourceServer = FindServer(user->server);
4141                         if (SourceServer)
4142                         {
4143                                 SourceServer->AddUserCount();
4144                         }
4145
4146                 }
4147         }
4148
4149         virtual void OnUserQuit(userrec* user, const std::string &reason)
4150         {
4151                 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
4152                 {
4153                         std::deque<std::string> params;
4154                         params.push_back(":"+reason);
4155                         DoOneToMany(user->nick,"QUIT",params);
4156                 }
4157                 // Regardless, We need to modify the user Counts..
4158                 TreeServer* SourceServer = FindServer(user->server);
4159                 if (SourceServer)
4160                 {
4161                         SourceServer->DelUserCount();
4162                 }
4163
4164         }
4165
4166         virtual void OnUserPostNick(userrec* user, const std::string &oldnick)
4167         {
4168                 if (IS_LOCAL(user))
4169                 {
4170                         std::deque<std::string> params;
4171                         params.push_back(user->nick);
4172                         DoOneToMany(oldnick,"NICK",params);
4173                 }
4174         }
4175
4176         virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, const std::string &reason)
4177         {
4178                 if ((source) && (IS_LOCAL(source)))
4179                 {
4180                         std::deque<std::string> params;
4181                         params.push_back(chan->name);
4182                         params.push_back(user->nick);
4183                         params.push_back(":"+reason);
4184                         DoOneToMany(source->nick,"KICK",params);
4185                 }
4186                 else if (!source)
4187                 {
4188                         std::deque<std::string> params;
4189                         params.push_back(chan->name);
4190                         params.push_back(user->nick);
4191                         params.push_back(":"+reason);
4192                         DoOneToMany(Srv->GetServerName(),"KICK",params);
4193                 }
4194         }
4195
4196         virtual void OnRemoteKill(userrec* source, userrec* dest, const std::string &reason)
4197         {
4198                 std::deque<std::string> params;
4199                 params.push_back(dest->nick);
4200                 params.push_back(":"+reason);
4201                 DoOneToMany(source->nick,"KILL",params);
4202         }
4203
4204         virtual void OnRehash(const std::string &parameter)
4205         {
4206                 if (parameter != "")
4207                 {
4208                         std::deque<std::string> params;
4209                         params.push_back(parameter);
4210                         DoOneToMany(Srv->GetServerName(),"REHASH",params);
4211                         // check for self
4212                         if (Srv->MatchText(Srv->GetServerName(),parameter))
4213                         {
4214                                 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
4215                                 Srv->RehashServer();
4216                         }
4217                 }
4218                 ReadConfiguration(false);
4219         }
4220
4221         // note: the protocol does not allow direct umode +o except
4222         // via NICK with 8 params. sending OPERTYPE infers +o modechange
4223         // locally.
4224         virtual void OnOper(userrec* user, const std::string &opertype)
4225         {
4226                 if (IS_LOCAL(user))
4227                 {
4228                         std::deque<std::string> params;
4229                         params.push_back(opertype);
4230                         DoOneToMany(user->nick,"OPERTYPE",params);
4231                 }
4232         }
4233
4234         void OnLine(userrec* source, const std::string &host, bool adding, char linetype, long duration, const std::string &reason)
4235         {
4236                 if (IS_LOCAL(source))
4237                 {
4238                         char type[8];
4239                         snprintf(type,8,"%cLINE",linetype);
4240                         std::string stype = type;
4241                         if (adding)
4242                         {
4243                                 char sduration[MAXBUF];
4244                                 snprintf(sduration,MAXBUF,"%ld",duration);
4245                                 std::deque<std::string> params;
4246                                 params.push_back(host);
4247                                 params.push_back(sduration);
4248                                 params.push_back(":"+reason);
4249                                 DoOneToMany(source->nick,stype,params);
4250                         }
4251                         else
4252                         {
4253                                 std::deque<std::string> params;
4254                                 params.push_back(host);
4255                                 DoOneToMany(source->nick,stype,params);
4256                         }
4257                 }
4258         }
4259
4260         virtual void OnAddGLine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
4261         {
4262                 OnLine(source,hostmask,true,'G',duration,reason);
4263         }
4264         
4265         virtual void OnAddZLine(long duration, userrec* source, const std::string &reason, const std::string &ipmask)
4266         {
4267                 OnLine(source,ipmask,true,'Z',duration,reason);
4268         }
4269
4270         virtual void OnAddQLine(long duration, userrec* source, const std::string &reason, const std::string &nickmask)
4271         {
4272                 OnLine(source,nickmask,true,'Q',duration,reason);
4273         }
4274
4275         virtual void OnAddELine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
4276         {
4277                 OnLine(source,hostmask,true,'E',duration,reason);
4278         }
4279
4280         virtual void OnDelGLine(userrec* source, const std::string &hostmask)
4281         {
4282                 OnLine(source,hostmask,false,'G',0,"");
4283         }
4284
4285         virtual void OnDelZLine(userrec* source, const std::string &ipmask)
4286         {
4287                 OnLine(source,ipmask,false,'Z',0,"");
4288         }
4289
4290         virtual void OnDelQLine(userrec* source, const std::string &nickmask)
4291         {
4292                 OnLine(source,nickmask,false,'Q',0,"");
4293         }
4294
4295         virtual void OnDelELine(userrec* source, const std::string &hostmask)
4296         {
4297                 OnLine(source,hostmask,false,'E',0,"");
4298         }
4299
4300         virtual void OnMode(userrec* user, void* dest, int target_type, const std::string &text)
4301         {
4302                 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
4303                 {
4304                         if (target_type == TYPE_USER)
4305                         {
4306                                 userrec* u = (userrec*)dest;
4307                                 std::deque<std::string> params;
4308                                 params.push_back(u->nick);
4309                                 params.push_back(text);
4310                                 DoOneToMany(user->nick,"MODE",params);
4311                         }
4312                         else
4313                         {
4314                                 chanrec* c = (chanrec*)dest;
4315                                 std::deque<std::string> params;
4316                                 params.push_back(c->name);
4317                                 params.push_back(text);
4318                                 DoOneToMany(user->nick,"MODE",params);
4319                         }
4320                 }
4321         }
4322
4323         virtual void OnSetAway(userrec* user)
4324         {
4325                 if (IS_LOCAL(user))
4326                 {
4327                         std::deque<std::string> params;
4328                         params.push_back(":"+std::string(user->awaymsg));
4329                         DoOneToMany(user->nick,"AWAY",params);
4330                 }
4331         }
4332
4333         virtual void OnCancelAway(userrec* user)
4334         {
4335                 if (IS_LOCAL(user))
4336                 {
4337                         std::deque<std::string> params;
4338                         params.clear();
4339                         DoOneToMany(user->nick,"AWAY",params);
4340                 }
4341         }
4342
4343         virtual void ProtoSendMode(void* opaque, int target_type, void* target, const std::string &modeline)
4344         {
4345                 TreeSocket* s = (TreeSocket*)opaque;
4346                 if (target)
4347                 {
4348                         if (target_type == TYPE_USER)
4349                         {
4350                                 userrec* u = (userrec*)target;
4351                                 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+ConvToStr(u->age)+" "+modeline);
4352                         }
4353                         else
4354                         {
4355                                 chanrec* c = (chanrec*)target;
4356                                 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+ConvToStr(c->age)+" "+modeline);
4357                         }
4358                 }
4359         }
4360
4361         virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, const std::string &extname, const std::string &extdata)
4362         {
4363                 TreeSocket* s = (TreeSocket*)opaque;
4364                 if (target)
4365                 {
4366                         if (target_type == TYPE_USER)
4367                         {
4368                                 userrec* u = (userrec*)target;
4369                                 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+u->nick+" "+extname+" :"+extdata);
4370                         }
4371                         else if (target_type == TYPE_OTHER)
4372                         {
4373                                 s->WriteLine(":"+Srv->GetServerName()+" METADATA * "+extname+" :"+extdata);
4374                         }
4375                         else if (target_type == TYPE_CHANNEL)
4376                         {
4377                                 chanrec* c = (chanrec*)target;
4378                                 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+c->name+" "+extname+" :"+extdata);
4379                         }
4380                 }
4381         }
4382
4383         virtual void OnEvent(Event* event)
4384         {
4385                 if (event->GetEventID() == "send_metadata")
4386                 {
4387                         std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
4388                         if (params->size() < 3)
4389                                 return;
4390                         (*params)[2] = ":" + (*params)[2];
4391                         DoOneToMany(Srv->GetServerName(),"METADATA",*params);
4392                 }
4393                 else if (event->GetEventID() == "send_mode")
4394                 {
4395                         std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
4396                         if (params->size() < 2)
4397                                 return;
4398                         // Insert the TS value of the object, either userrec or chanrec
4399                         time_t ourTS = 0;
4400                         userrec* a = Srv->FindNick((*params)[0]);
4401                         if (a)
4402                         {
4403                                 ourTS = a->age;
4404                         }
4405                         else
4406                         {
4407                                 chanrec* a = Srv->FindChannel((*params)[0]);
4408                                 if (a)
4409                                 {
4410                                         ourTS = a->age;
4411                                 }
4412                         }
4413                         params->insert(params->begin() + 1,ConvToStr(ourTS));
4414                         DoOneToMany(Srv->GetServerName(),"FMODE",*params);
4415                 }
4416         }
4417
4418         virtual ~ModuleSpanningTree()
4419         {
4420         }
4421
4422         virtual Version GetVersion()
4423         {
4424                 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
4425         }
4426
4427         void Implements(char* List)
4428         {
4429                 List[I_OnPreCommand] = List[I_OnGetServerDescription] = List[I_OnUserInvite] = List[I_OnPostLocalTopicChange] = 1;
4430                 List[I_OnWallops] = List[I_OnUserNotice] = List[I_OnUserMessage] = List[I_OnBackgroundTimer] = 1;
4431                 List[I_OnUserJoin] = List[I_OnChangeHost] = List[I_OnChangeName] = List[I_OnUserPart] = List[I_OnUserConnect] = 1;
4432                 List[I_OnUserQuit] = List[I_OnUserPostNick] = List[I_OnUserKick] = List[I_OnRemoteKill] = List[I_OnRehash] = 1;
4433                 List[I_OnOper] = List[I_OnAddGLine] = List[I_OnAddZLine] = List[I_OnAddQLine] = List[I_OnAddELine] = 1;
4434                 List[I_OnDelGLine] = List[I_OnDelZLine] = List[I_OnDelQLine] = List[I_OnDelELine] = List[I_ProtoSendMode] = List[I_OnMode] = 1;
4435                 List[I_OnStats] = List[I_ProtoSendMetaData] = List[I_OnEvent] = List[I_OnSetAway] = List[I_OnCancelAway] = 1;
4436         }
4437
4438         /* It is IMPORTANT that m_spanningtree is the last module in the chain
4439          * so that any activity it sees is FINAL, e.g. we arent going to send out
4440          * a NICK message before m_cloaking has finished putting the +x on the user,
4441          * etc etc.
4442          * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
4443          * the module call queue.
4444          */
4445         Priority Prioritize()
4446         {
4447                 return PRIORITY_LAST;
4448         }
4449 };
4450
4451
4452 class ModuleSpanningTreeFactory : public ModuleFactory
4453 {
4454  public:
4455         ModuleSpanningTreeFactory()
4456         {
4457         }
4458         
4459         ~ModuleSpanningTreeFactory()
4460         {
4461         }
4462         
4463         virtual Module * CreateModule(Server* Me)
4464         {
4465                 TreeProtocolModule = new ModuleSpanningTree(Me);
4466                 return TreeProtocolModule;
4467         }
4468         
4469 };
4470
4471
4472 extern "C" void * init_module( void )
4473 {
4474         return new ModuleSpanningTreeFactory;
4475 }