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