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