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