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