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