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