]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree.cpp
Now uses two AES contexts, an 'in' context and an 'out' context
[user/henk/code/inspircd.git] / src / modules / m_spanningtree.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  Inspire is copyright (C) 2002-2005 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 #ifdef GCC3
27 #include <ext/hash_map>
28 #else
29 #include <hash_map>
30 #endif
31 #include "users.h"
32 #include "channels.h"
33 #include "modules.h"
34 #include "commands.h"
35 #include "socket.h"
36 #include "helperfuncs.h"
37 #include "inspircd.h"
38 #include "inspstring.h"
39 #include "hashcomp.h"
40 #include "message.h"
41 #include "xline.h"
42 #include "typedefs.h"
43 #include "cull_list.h"
44 #include "aes.h"
45
46 #ifdef GCC3
47 #define nspace __gnu_cxx
48 #else
49 #define nspace std
50 #endif
51
52 /*
53  * The server list in InspIRCd is maintained as two structures
54  * which hold the data in different ways. Most of the time, we
55  * want to very quicky obtain three pieces of information:
56  *
57  * (1) The information on a server
58  * (2) The information on the server we must send data through
59  *     to actually REACH the server we're after
60  * (3) Potentially, the child/parent objects of this server
61  *
62  * The InspIRCd spanning protocol provides easy access to these
63  * by storing the data firstly in a recursive structure, where
64  * each item references its parent item, and a dynamic list
65  * of child items, and another structure which stores the items
66  * hashed, linearly. This means that if we want to find a server
67  * by name quickly, we can look it up in the hash, avoiding
68  * any O(n) lookups. If however, during a split or sync, we want
69  * to apply an operation to a server, and any of its child objects
70  * we can resort to recursion to walk the tree structure.
71  */
72
73 class ModuleSpanningTree;
74 static ModuleSpanningTree* TreeProtocolModule;
75
76 extern ServerConfig* Config;
77
78 extern std::vector<Module*> modules;
79 extern std::vector<ircd_module*> factory;
80 extern int MODCOUNT;
81
82 /* Any socket can have one of five states at any one time.
83  * The LISTENER state indicates a socket which is listening
84  * for connections. It cannot receive data itself, only incoming
85  * sockets.
86  * The CONNECTING state indicates an outbound socket which is
87  * waiting to be writeable.
88  * The WAIT_AUTH_1 state indicates the socket is outbound and
89  * has successfully connected, but has not yet sent and received
90  * SERVER strings.
91  * The WAIT_AUTH_2 state indicates that the socket is inbound
92  * (allocated by a LISTENER) but has not yet sent and received
93  * SERVER strings.
94  * The CONNECTED state represents a fully authorized, fully
95  * connected server.
96  */
97 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
98
99 /* We need to import these from the core for use in netbursts */
100 extern user_hash clientlist;
101 extern chan_hash chanlist;
102
103 /* Foward declarations */
104 class TreeServer;
105 class TreeSocket;
106
107 /* This variable represents the root of the server tree
108  * (for all intents and purposes, it's us)
109  */
110 TreeServer *TreeRoot;
111
112 Server* Srv;
113
114 /* This hash_map holds the hash equivalent of the server
115  * tree, used for rapid linear lookups.
116  */
117 typedef nspace::hash_map<std::string, TreeServer*> server_hash;
118 server_hash serverlist;
119
120 /* More forward declarations */
121 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> &params, std::string target);
122 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> &params, std::string omit);
123 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> &params);
124 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, std::string command, std::deque<std::string> &params);
125 void ReadConfiguration(bool rebind);
126
127 /* Imported from xline.cpp for use during netburst */
128 extern std::vector<KLine> klines;
129 extern std::vector<GLine> glines;
130 extern std::vector<ZLine> zlines;
131 extern std::vector<QLine> qlines;
132 extern std::vector<ELine> elines;
133 extern std::vector<KLine> pklines;
134 extern std::vector<GLine> pglines;
135 extern std::vector<ZLine> pzlines;
136 extern std::vector<QLine> pqlines;
137 extern std::vector<ELine> pelines;
138
139 /* Each server in the tree is represented by one class of
140  * type TreeServer. A locally connected TreeServer can
141  * have a class of type TreeSocket associated with it, for
142  * remote servers, the TreeSocket entry will be NULL.
143  * Each server also maintains a pointer to its parent
144  * (NULL if this server is ours, at the top of the tree)
145  * and a pointer to its "Route" (see the comments in the
146  * constructors below), and also a dynamic list of pointers
147  * to its children which can be iterated recursively
148  * if required. Creating or deleting objects of type
149  * TreeServer automatically maintains the hash_map of
150  * TreeServer items, deleting and inserting them as they
151  * are created and destroyed.
152  */
153
154 class TreeServer
155 {
156         TreeServer* Parent;                     /* Parent entry */
157         TreeServer* Route;                      /* Route entry */
158         std::vector<TreeServer*> Children;      /* List of child objects */
159         std::string ServerName;                 /* Server's name */
160         std::string ServerDesc;                 /* Server's description */
161         std::string VersionString;              /* Version string or empty string */
162         int UserCount;                          /* Not used in this version */
163         int OperCount;                          /* Not used in this version */
164         TreeSocket* Socket;                     /* For directly connected servers this points at the socket object */
165         time_t NextPing;                        /* After this time, the server should be PINGed*/
166         bool LastPingWasGood;                   /* True if the server responded to the last PING with a PONG */
167         
168  public:
169
170         /* We don't use this constructor. Its a dummy, and won't cause any insertion
171          * of the TreeServer into the hash_map. See below for the two we DO use.
172          */
173         TreeServer()
174         {
175                 Parent = NULL;
176                 ServerName = "";
177                 ServerDesc = "";
178                 VersionString = "";
179                 UserCount = OperCount = 0;
180                 VersionString = Srv->GetVersion();
181         }
182
183         /* We use this constructor only to create the 'root' item, TreeRoot, which
184          * represents our own server. Therefore, it has no route, no parent, and
185          * no socket associated with it. Its version string is our own local version.
186          */
187         TreeServer(std::string Name, std::string Desc) : ServerName(Name), ServerDesc(Desc)
188         {
189                 Parent = NULL;
190                 VersionString = "";
191                 UserCount = OperCount = 0;
192                 VersionString = Srv->GetVersion();
193                 Route = NULL;
194                 Socket = NULL; /* Fix by brain */
195                 AddHashEntry();
196         }
197
198         /* When we create a new server, we call this constructor to initialize it.
199          * This constructor initializes the server's Route and Parent, and sets up
200          * its ping counters so that it will be pinged one minute from now.
201          */
202         TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name), ServerDesc(Desc), Socket(Sock)
203         {
204                 VersionString = "";
205                 UserCount = OperCount = 0;
206                 this->SetNextPingTime(time(NULL) + 60);
207                 this->SetPingFlag();
208
209                 /* find the 'route' for this server (e.g. the one directly connected
210                  * to the local server, which we can use to reach it)
211                  *
212                  * In the following example, consider we have just added a TreeServer
213                  * class for server G on our network, of which we are server A.
214                  * To route traffic to G (marked with a *) we must send the data to
215                  * B (marked with a +) so this algorithm initializes the 'Route'
216                  * value to point at whichever server traffic must be routed through
217                  * to get here. If we were to try this algorithm with server B,
218                  * the Route pointer would point at its own object ('this').
219                  *
220                  *              A
221                  *             / \
222                  *          + B   C
223                  *           / \   \
224                  *          D   E   F
225                  *         /         \
226                  *      * G           H
227                  *
228                  * We only run this algorithm when a server is created, as
229                  * the routes remain constant while ever the server exists, and
230                  * do not need to be re-calculated.
231                  */
232
233                 Route = Above;
234                 if (Route == TreeRoot)
235                 {
236                         Route = this;
237                 }
238                 else
239                 {
240                         while (this->Route->GetParent() != TreeRoot)
241                         {
242                                 this->Route = Route->GetParent();
243                         }
244                 }
245
246                 /* Because recursive code is slow and takes a lot of resources,
247                  * we store two representations of the server tree. The first
248                  * is a recursive structure where each server references its
249                  * children and its parent, which is used for netbursts and
250                  * netsplits to dump the whole dataset to the other server,
251                  * and the second is used for very fast lookups when routing
252                  * messages and is instead a hash_map, where each item can
253                  * be referenced by its server name. The AddHashEntry()
254                  * call below automatically inserts each TreeServer class
255                  * into the hash_map as it is created. There is a similar
256                  * maintainance call in the destructor to tidy up deleted
257                  * servers.
258                  */
259
260                 this->AddHashEntry();
261         }
262
263         /* This method is used to add the structure to the
264          * hash_map for linear searches. It is only called
265          * by the constructors.
266          */
267         void AddHashEntry()
268         {
269                 server_hash::iterator iter;
270                 iter = serverlist.find(this->ServerName);
271                 if (iter == serverlist.end())
272                         serverlist[this->ServerName] = this;
273         }
274
275         /* This method removes the reference to this object
276          * from the hash_map which is used for linear searches.
277          * It is only called by the default destructor.
278          */
279         void DelHashEntry()
280         {
281                 server_hash::iterator iter;
282                 iter = serverlist.find(this->ServerName);
283                 if (iter != serverlist.end())
284                         serverlist.erase(iter);
285         }
286
287         /* These accessors etc should be pretty self-
288          * explanitory.
289          */
290
291         TreeServer* GetRoute()
292         {
293                 return Route;
294         }
295
296         std::string GetName()
297         {
298                 return ServerName;
299         }
300
301         std::string GetDesc()
302         {
303                 return ServerDesc;
304         }
305
306         std::string GetVersion()
307         {
308                 return VersionString;
309         }
310
311         void SetNextPingTime(time_t t)
312         {
313                 this->NextPing = t;
314                 LastPingWasGood = false;
315         }
316
317         time_t NextPingTime()
318         {
319                 return NextPing;
320         }
321
322         bool AnsweredLastPing()
323         {
324                 return LastPingWasGood;
325         }
326
327         void SetPingFlag()
328         {
329                 LastPingWasGood = true;
330         }
331
332         int GetUserCount()
333         {
334                 return UserCount;
335         }
336
337         int GetOperCount()
338         {
339                 return OperCount;
340         }
341
342         TreeSocket* GetSocket()
343         {
344                 return Socket;
345         }
346
347         TreeServer* GetParent()
348         {
349                 return Parent;
350         }
351
352         void SetVersion(std::string Version)
353         {
354                 VersionString = Version;
355         }
356
357         unsigned int ChildCount()
358         {
359                 return Children.size();
360         }
361
362         TreeServer* GetChild(unsigned int n)
363         {
364                 if (n < Children.size())
365                 {
366                         /* Make sure they  cant request
367                          * an out-of-range object. After
368                          * all we know what these programmer
369                          * types are like *grin*.
370                          */
371                         return Children[n];
372                 }
373                 else
374                 {
375                         return NULL;
376                 }
377         }
378
379         void AddChild(TreeServer* Child)
380         {
381                 Children.push_back(Child);
382         }
383
384         bool DelChild(TreeServer* Child)
385         {
386                 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
387                 {
388                         if (*a == Child)
389                         {
390                                 Children.erase(a);
391                                 return true;
392                         }
393                 }
394                 return false;
395         }
396
397         /* Removes child nodes of this node, and of that node, etc etc.
398          * This is used during netsplits to automatically tidy up the
399          * server tree. It is slow, we don't use it for much else.
400          */
401         bool Tidy()
402         {
403                 bool stillchildren = true;
404                 while (stillchildren)
405                 {
406                         stillchildren = false;
407                         for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
408                         {
409                                 TreeServer* s = (TreeServer*)*a;
410                                 s->Tidy();
411                                 Children.erase(a);
412                                 delete s;
413                                 stillchildren = true;
414                                 break;
415                         }
416                 }
417                 return true;
418         }
419
420         ~TreeServer()
421         {
422                 /* We'd better tidy up after ourselves, eh? */
423                 this->DelHashEntry();
424         }
425 };
426
427 /* The Link class might as well be a struct,
428  * but this is C++ and we don't believe in structs (!).
429  * It holds the entire information of one <link>
430  * tag from the main config file. We maintain a list
431  * of them, and populate the list on rehash/load.
432  */
433
434 class Link
435 {
436  public:
437          std::string Name;
438          std::string IPAddr;
439          int Port;
440          std::string SendPass;
441          std::string RecvPass;
442          unsigned long AutoConnect;
443          time_t NextConnectTime;
444          std::string EncryptionKey;
445 };
446
447 /* The usual stuff for inspircd modules,
448  * plus the vector of Link classes which we
449  * use to store the <link> tags from the config
450  * file.
451  */
452 ConfigReader *Conf;
453 std::vector<Link> LinkBlocks;
454
455 /* Yay for fast searches!
456  * This is hundreds of times faster than recursion
457  * or even scanning a linked list, especially when
458  * there are more than a few servers to deal with.
459  * (read as: lots).
460  */
461 TreeServer* FindServer(std::string ServerName)
462 {
463         server_hash::iterator iter;
464         iter = serverlist.find(ServerName);
465         if (iter != serverlist.end())
466         {
467                 return iter->second;
468         }
469         else
470         {
471                 return NULL;
472         }
473 }
474
475 /* Returns the locally connected server we must route a
476  * message through to reach server 'ServerName'. This
477  * only applies to one-to-one and not one-to-many routing.
478  * See the comments for the constructor of TreeServer
479  * for more details.
480  */
481 TreeServer* BestRouteTo(std::string ServerName)
482 {
483         if (ServerName.c_str() == TreeRoot->GetName())
484                 return NULL;
485         TreeServer* Found = FindServer(ServerName);
486         if (Found)
487         {
488                 return Found->GetRoute();
489         }
490         else
491         {
492                 return NULL;
493         }
494 }
495
496 /* Find the first server matching a given glob mask.
497  * Theres no find-using-glob method of hash_map [awwww :-(]
498  * so instead, we iterate over the list using an iterator
499  * and match each one until we get a hit. Yes its slow,
500  * deal with it.
501  */
502 TreeServer* FindServerMask(std::string ServerName)
503 {
504         for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
505         {
506                 if (Srv->MatchText(i->first,ServerName))
507                         return i->second;
508         }
509         return NULL;
510 }
511
512 /* A convenient wrapper that returns true if a server exists */
513 bool IsServer(std::string ServerName)
514 {
515         return (FindServer(ServerName) != NULL);
516 }
517
518 /* Every SERVER connection inbound or outbound is represented by
519  * an object of type TreeSocket.
520  * TreeSockets, being inherited from InspSocket, can be tied into
521  * the core socket engine, and we cn therefore receive activity events
522  * for them, just like activex objects on speed. (yes really, that
523  * is a technical term!) Each of these which relates to a locally
524  * connected server is assocated with it, by hooking it onto a
525  * TreeSocket class using its constructor. In this way, we can
526  * maintain a list of servers, some of which are directly connected,
527  * some of which are not.
528  */
529
530 class TreeSocket : public InspSocket
531 {
532         std::string myhost;
533         std::string in_buffer;
534         ServerState LinkState;
535         std::string InboundServerName;
536         std::string InboundDescription;
537         int num_lost_users;
538         int num_lost_servers;
539         time_t NextPing;
540         bool LastPingWasGood;
541         bool bursting;
542         AES* ctx_in;
543         AES* ctx_out;
544         unsigned int keylength;
545         
546  public:
547
548         /* Because most of the I/O gubbins are encapsulated within
549          * InspSocket, we just call the superclass constructor for
550          * most of the action, and append a few of our own values
551          * to it.
552          */
553         TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
554                 : InspSocket(host, port, listening, maxtime)
555         {
556                 myhost = host;
557                 this->LinkState = LISTENER;
558                 this->ctx_in = NULL;
559                 this->ctx_out = NULL;
560         }
561
562         TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
563                 : InspSocket(host, port, listening, maxtime)
564         {
565                 myhost = ServerName;
566                 this->LinkState = CONNECTING;
567                 this->ctx_in = NULL;
568                 this->ctx_out = NULL;
569         }
570
571         /* When a listening socket gives us a new file descriptor,
572          * we must associate it with a socket without creating a new
573          * connection. This constructor is used for this purpose.
574          */
575         TreeSocket(int newfd, char* ip)
576                 : InspSocket(newfd, ip)
577         {
578                 this->LinkState = WAIT_AUTH_1;
579                 this->ctx_in = NULL;
580                 this->ctx_out = NULL;
581                 this->SendCapabilities();
582         }
583
584         ~TreeSocket()
585         {
586                 if (ctx_in)
587                         delete ctx_in;
588                 if (ctx_out)
589                         delete ctx_out;
590         }
591
592         void InitAES(std::string key,std::string SName)
593         {
594                 if (key == "")
595                         return;
596
597                 ctx_in = new AES();
598                 ctx_out = new AES();
599                 log(DEBUG,"Initialized AES key %s",key.c_str());
600                 // key must be 16, 24, 32 etc bytes (multiple of 8)
601                 keylength = key.length();
602                 if (!(keylength == 16 || keylength == 24 || keylength == 32))
603                 {
604                         WriteOpers("*** \2ERROR\2: Key length for encryptionkey is not 16, 24 or 32 bytes in length!");
605                         log(DEBUG,"Key length not 16, 24 or 32 characters!");
606                 }
607                 else
608                 {
609                         WriteOpers("*** \2AES\2: Initialized %d bit encryption to server %s",keylength*8,SName.c_str());
610                         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\
611                                 \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);
612                         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\
613                                 \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);
614                 }
615         }
616         
617         /* When an outbound connection finishes connecting, we receive
618          * this event, and must send our SERVER string to the other
619          * side. If the other side is happy, as outlined in the server
620          * to server docs on the inspircd.org site, the other side
621          * will then send back its own server string.
622          */
623         virtual bool OnConnected()
624         {
625                 if (this->LinkState == CONNECTING)
626                 {
627                         Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
628                         /* we do not need to change state here. */
629                         for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
630                         {
631                                 if (x->Name == this->myhost)
632                                 {
633                                         this->SendCapabilities();
634                                         if (x->EncryptionKey != "")
635                                         {
636                                                 if (!(x->EncryptionKey.length() == 16 || x->EncryptionKey.length() == 24 || x->EncryptionKey.length() == 32))
637                                                 {
638                                                         WriteOpers("\2WARNING\2: Your encryption key is NOT 16, 24 or 32 characters in length, encryption will \2NOT\2 be enabled.");
639                                                 }
640                                                 else
641                                                 {
642                                                         this->WriteLine("AES "+Srv->GetServerName());
643                                                         this->InitAES(x->EncryptionKey,x->Name);
644                                                 }
645                                         }
646                                         /* found who we're supposed to be connecting to, send the neccessary gubbins. */
647                                         this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
648                                         return true;
649                                 }
650                         }
651                 }
652                 /* There is a (remote) chance that between the /CONNECT and the connection
653                  * being accepted, some muppet has removed the <link> block and rehashed.
654                  * If that happens the connection hangs here until it's closed. Unlikely
655                  * and rather harmless.
656                  */
657                 return true;
658         }
659         
660         virtual void OnError(InspSocketError e)
661         {
662                 /* We don't handle this method, because all our
663                  * dirty work is done in OnClose() (see below)
664                  * which is still called on error conditions too.
665                  */
666         }
667
668         virtual int OnDisconnect()
669         {
670                 /* For the same reason as above, we don't
671                  * handle OnDisconnect()
672                  */
673                 return true;
674         }
675
676         /* Recursively send the server tree with distances as hops.
677          * This is used during network burst to inform the other server
678          * (and any of ITS servers too) of what servers we know about.
679          * If at any point any of these servers already exist on the other
680          * end, our connection may be terminated. The hopcounts given
681          * by this function are relative, this doesn't matter so long as
682          * they are all >1, as all the remote servers re-calculate them
683          * to be relative too, with themselves as hop 0.
684          */
685         void SendServers(TreeServer* Current, TreeServer* s, int hops)
686         {
687                 char command[1024];
688                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
689                 {
690                         TreeServer* recursive_server = Current->GetChild(q);
691                         if (recursive_server != s)
692                         {
693                                 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
694                                 this->WriteLine(command);
695                                 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
696                                 /* down to next level */
697                                 this->SendServers(recursive_server, s, hops+1);
698                         }
699                 }
700         }
701
702         std::string MyCapabilities()
703         {
704                 ServerConfig* Config = Srv->GetConfig();
705                 std::vector<std::string> modlist;
706                 std::string capabilities = "";
707
708                 for (int i = 0; i <= MODCOUNT; i++)
709                 {
710                         if ((modules[i]->GetVersion().Flags & VF_STATIC) || (modules[i]->GetVersion().Flags & VF_COMMON))
711                                 modlist.push_back(Config->module_names[i]);
712                 }
713                 sort(modlist.begin(),modlist.end());
714                 for (unsigned int i = 0; i < modlist.size(); i++)
715                 {
716                         if (i)
717                                 capabilities = capabilities + ",";
718                         capabilities = capabilities + modlist[i];
719                 }
720                 return capabilities;
721         }
722         
723         void SendCapabilities()
724         {
725                 this->WriteLine("CAPAB "+MyCapabilities());
726         }
727
728         bool Capab(std::deque<std::string> params)
729         {
730                 if (params.size() != 1)
731                 {
732                         this->WriteLine("ERROR :Invalid number of parameters for CAPAB");
733                         return false;
734                 }
735                 if (params[0] != this->MyCapabilities())
736                 {
737                         std::string quitserver = this->myhost;
738                         if (this->InboundServerName != "")
739                         {
740                                 quitserver = this->InboundServerName;
741                         }
742                         WriteOpers("*** \2ERROR\2: Server '%s' does not have the same set of modules loaded, cannot link!",quitserver.c_str());
743                         WriteOpers("*** Our networked module set is: '%s'",this->MyCapabilities().c_str());
744                         WriteOpers("*** Other server's networked module set is: '%s'",params[0].c_str());
745                         WriteOpers("*** These lists must match exactly on both servers. Please correct these errors, and try again.");
746                         this->WriteLine("ERROR :CAPAB mismatch; My capabilities: '"+this->MyCapabilities()+"'");
747                         return false;
748                 }
749                 return true;
750         }
751
752         /* This function forces this server to quit, removing this server
753          * and any users on it (and servers and users below that, etc etc).
754          * It's very slow and pretty clunky, but luckily unless your network
755          * is having a REAL bad hair day, this function shouldnt be called
756          * too many times a month ;-)
757          */
758         void SquitServer(TreeServer* Current, CullList* Goners)
759         {
760                 /* recursively squit the servers attached to 'Current'.
761                  * We're going backwards so we don't remove users
762                  * while we still need them ;)
763                  */
764                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
765                 {
766                         TreeServer* recursive_server = Current->GetChild(q);
767                         this->SquitServer(recursive_server,Goners);
768                 }
769                 /* Now we've whacked the kids, whack self */
770                 num_lost_servers++;
771                 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
772                 {
773                         if (!strcasecmp(u->second->server,Current->GetName().c_str()))
774                         {
775                                 std::string qreason = Current->GetName()+" "+std::string(Srv->GetServerName());
776                                 Goners->AddItem(u->second,qreason);
777                                 num_lost_users++;
778                         }
779                 }
780         }
781
782         /* This is a wrapper function for SquitServer above, which
783          * does some validation first and passes on the SQUIT to all
784          * other remaining servers.
785          */
786         void Squit(TreeServer* Current,std::string reason)
787         {
788                 if ((Current) && (Current != TreeRoot))
789                 {
790                         std::deque<std::string> params;
791                         params.push_back(Current->GetName());
792                         params.push_back(":"+reason);
793                         DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
794                         if (Current->GetParent() == TreeRoot)
795                         {
796                                 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
797                         }
798                         else
799                         {
800                                 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
801                         }
802                         num_lost_servers = 0;
803                         num_lost_users = 0;
804                         CullList* Goners = new CullList();
805                         SquitServer(Current, Goners);
806                         Goners->Apply();
807                         Current->Tidy();
808                         Current->GetParent()->DelChild(Current);
809                         delete Current;
810                         delete Goners;
811                         WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
812                 }
813                 else
814                 {
815                         log(DEFAULT,"Squit from unknown server");
816                 }
817         }
818
819         /* FMODE command */
820         bool ForceMode(std::string source, std::deque<std::string> params)
821         {
822                 userrec* who = new userrec;
823                 who->fd = FD_MAGIC_NUMBER;
824                 if (params.size() < 2)
825                         return true;
826                 char* modelist[255];
827                 for (unsigned int q = 0; q < params.size(); q++)
828                 {
829                         modelist[q] = (char*)params[q].c_str();
830                 }
831                 Srv->SendMode(modelist,params.size(),who);
832                 DoOneToAllButSender(source,"FMODE",params,source);
833                 delete who;
834                 return true;
835         }
836
837         /* FTOPIC command */
838         bool ForceTopic(std::string source, std::deque<std::string> params)
839         {
840                 if (params.size() != 4)
841                         return true;
842                 std::string channel = params[0];
843                 time_t ts = atoi(params[1].c_str());
844                 std::string setby = params[2];
845                 std::string topic = params[3];
846
847                 chanrec* c = Srv->FindChannel(channel);
848                 if (c)
849                 {
850                         if ((ts >= c->topicset) || (!*c->topic))
851                         {
852                                 std::string oldtopic = c->topic;
853                                 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
854                                 strlcpy(c->setby,setby.c_str(),NICKMAX);
855                                 c->topicset = ts;
856                                 /* if the topic text is the same as the current topic,
857                                  * dont bother to send the TOPIC command out, just silently
858                                  * update the set time and set nick.
859                                  */
860                                 if (oldtopic != topic)
861                                         WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
862                         }
863                         
864                 }
865                 
866                 /* all done, send it on its way */
867                 params[3] = ":" + params[3];
868                 DoOneToAllButSender(source,"FTOPIC",params,source);
869
870                 return true;
871         }
872
873         /* FJOIN, similar to unreal SJOIN */
874         bool ForceJoin(std::string source, std::deque<std::string> params)
875         {
876                 if (params.size() < 3)
877                         return true;
878
879                 char first[MAXBUF];
880                 char modestring[MAXBUF];
881                 char* mode_users[127];
882                 mode_users[0] = first;
883                 mode_users[1] = modestring;
884                 strcpy(mode_users[1],"+");
885                 unsigned int modectr = 2;
886                 
887                 userrec* who = NULL;
888                 std::string channel = params[0];
889                 time_t TS = atoi(params[1].c_str());
890                 char* key = "";
891                 
892                 chanrec* chan = Srv->FindChannel(channel);
893                 if (chan)
894                 {
895                         key = chan->key;
896                 }
897                 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
898
899                 /* default is a high value, which if we dont have this
900                  * channel will let the other side apply their modes.
901                  */
902                 time_t ourTS = time(NULL)+600;
903                 chanrec* us = Srv->FindChannel(channel);
904                 if (us)
905                 {
906                         ourTS = us->age;
907                 }
908
909                 log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
910
911                 /* do this first, so our mode reversals are correctly received by other servers
912                  * if there is a TS collision.
913                  */
914                 DoOneToAllButSender(source,"FJOIN",params,source);
915                 
916                 for (unsigned int usernum = 2; usernum < params.size(); usernum++)
917                 {
918                         /* process one channel at a time, applying modes. */
919                         char* usr = (char*)params[usernum].c_str();
920                         char permissions = *usr;
921                         switch (permissions)
922                         {
923                                 case '@':
924                                         usr++;
925                                         mode_users[modectr++] = usr;
926                                         strlcat(modestring,"o",MAXBUF);
927                                 break;
928                                 case '%':
929                                         usr++;
930                                         mode_users[modectr++] = usr;
931                                         strlcat(modestring,"h",MAXBUF);
932                                 break;
933                                 case '+':
934                                         usr++;
935                                         mode_users[modectr++] = usr;
936                                         strlcat(modestring,"v",MAXBUF);
937                                 break;
938                         }
939                         who = Srv->FindNick(usr);
940                         if (who)
941                         {
942                                 Srv->JoinUserToChannel(who,channel,key);
943                                 if (modectr >= (MAXMODES-1))
944                                 {
945                                         /* theres a mode for this user. push them onto the mode queue, and flush it
946                                          * if there are more than MAXMODES to go.
947                                          */
948                                         if ((ourTS >= TS) || (Srv->IsUlined(who->server)))
949                                         {
950                                                 /* We also always let u-lined clients win, no matter what the TS value */
951                                                 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
952                                                 Srv->SendMode(mode_users,modectr,who);
953                                         }
954                                         else
955                                         {
956                                                 log(DEBUG,"Their channel newer than ours, bouncing their modes");
957                                                 /* bouncy bouncy! */
958                                                 std::deque<std::string> params;
959                                                 /* modes are now being UNSET... */
960                                                 *mode_users[1] = '-';
961                                                 for (unsigned int x = 0; x < modectr; x++)
962                                                 {
963                                                         params.push_back(mode_users[x]);
964                                                 }
965                                                 // tell everyone to bounce the modes. bad modes, bad!
966                                                 DoOneToMany(Srv->GetServerName(),"FMODE",params);
967                                         }
968                                         strcpy(mode_users[1],"+");
969                                         modectr = 2;
970                                 }
971                         }
972                 }
973                 /* there werent enough modes built up to flush it during FJOIN,
974                  * or, there are a number left over. flush them out.
975                  */
976                 if ((modectr > 2) && (who))
977                 {
978                         if (ourTS >= TS)
979                         {
980                                 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
981                                 Srv->SendMode(mode_users,modectr,who);
982                         }
983                         else
984                         {
985                                 log(DEBUG,"Their channel newer than ours, bouncing their modes");
986                                 std::deque<std::string> params;
987                                 *mode_users[1] = '-';
988                                 for (unsigned int x = 0; x < modectr; x++)
989                                 {
990                                         params.push_back(mode_users[x]);
991                                 }
992                                 DoOneToMany(Srv->GetServerName(),"FMODE",params);
993                         }
994                 }
995                 return true;
996         }
997
998         /* NICK command */
999         bool IntroduceClient(std::string source, std::deque<std::string> params)
1000         {
1001                 if (params.size() < 8)
1002                         return true;
1003                 // NICK age nick host dhost ident +modes ip :gecos
1004                 //       0   1    2    3      4     5    6   7
1005                 std::string nick = params[1];
1006                 std::string host = params[2];
1007                 std::string dhost = params[3];
1008                 std::string ident = params[4];
1009                 time_t age = atoi(params[0].c_str());
1010                 std::string modes = params[5];
1011                 while (*(modes.c_str()) == '+')
1012                 {
1013                         char* m = (char*)modes.c_str();
1014                         m++;
1015                         modes = m;
1016                 }
1017                 std::string ip = params[6];
1018                 std::string gecos = params[7];
1019                 char* tempnick = (char*)nick.c_str();
1020                 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
1021                 
1022                 user_hash::iterator iter;
1023                 iter = clientlist.find(tempnick);
1024                 if (iter != clientlist.end())
1025                 {
1026                         // nick collision
1027                         log(DEBUG,"Nick collision on %s!%s@%s: %lu %lu",tempnick,ident.c_str(),host.c_str(),(unsigned long)age,(unsigned long)iter->second->age);
1028                         this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
1029                         return true;
1030                 }
1031
1032                 clientlist[tempnick] = new userrec();
1033                 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
1034                 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
1035                 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
1036                 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
1037                 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
1038                 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
1039                 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
1040                 clientlist[tempnick]->registered = 7;
1041                 clientlist[tempnick]->signon = age;
1042                 strlcpy(clientlist[tempnick]->modes, modes.c_str(),53);
1043                 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
1044
1045                 ucrec a;
1046                 a.channel = NULL;
1047                 a.uc_modes = 0;
1048                 for (int i = 0; i < MAXCHANS; i++)
1049                         clientlist[tempnick]->chans.push_back(a);
1050
1051                 if (!this->bursting)
1052                 {
1053                         WriteOpers("*** Client connecting at %s: %s!%s@%s [%s]",clientlist[tempnick]->server,clientlist[tempnick]->nick,clientlist[tempnick]->ident,clientlist[tempnick]->host,clientlist[tempnick]->ip);
1054                 }
1055                 params[7] = ":" + params[7];
1056                 DoOneToAllButSender(source,"NICK",params,source);
1057                 return true;
1058         }
1059
1060         /* Send one or more FJOINs for a channel of users.
1061          * If the length of a single line is more than 480-NICKMAX
1062          * in length, it is split over multiple lines.
1063          */
1064         void SendFJoins(TreeServer* Current, chanrec* c)
1065         {
1066                 log(DEBUG,"Sending FJOINs to other server for %s",c->name);
1067                 char list[MAXBUF];
1068                 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1069                 std::vector<char*> *ulist = c->GetUsers();
1070                 for (unsigned int i = 0; i < ulist->size(); i++)
1071                 {
1072                         char* o = (*ulist)[i];
1073                         userrec* otheruser = (userrec*)o;
1074                         strlcat(list," ",MAXBUF);
1075                         strlcat(list,cmode(otheruser,c),MAXBUF);
1076                         strlcat(list,otheruser->nick,MAXBUF);
1077                         if (strlen(list)>(480-NICKMAX))
1078                         {
1079                                 log(DEBUG,"FJOIN line wrapped");
1080                                 this->WriteLine(list);
1081                                 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
1082                         }
1083                 }
1084                 if (list[strlen(list)-1] != ':')
1085                 {
1086                         log(DEBUG,"Final FJOIN line");
1087                         this->WriteLine(list);
1088                 }
1089         }
1090
1091         /* Send G, Q, Z and E lines */
1092         void SendXLines(TreeServer* Current)
1093         {
1094                 char data[MAXBUF];
1095                 /* Yes, these arent too nice looking, but they get the job done */
1096                 for (std::vector<ZLine>::iterator i = zlines.begin(); i != zlines.end(); i++)
1097                 {
1098                         snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->ipaddr,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1099                         this->WriteLine(data);
1100                 }
1101                 for (std::vector<QLine>::iterator i = qlines.begin(); i != qlines.end(); i++)
1102                 {
1103                         snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->nick,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1104                         this->WriteLine(data);
1105                 }
1106                 for (std::vector<GLine>::iterator i = glines.begin(); i != glines.end(); i++)
1107                 {
1108                         snprintf(data,MAXBUF,":%s ADDLINE G %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1109                         this->WriteLine(data);
1110                 }
1111                 for (std::vector<ELine>::iterator i = elines.begin(); i != elines.end(); i++)
1112                 {
1113                         snprintf(data,MAXBUF,":%s ADDLINE E %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1114                         this->WriteLine(data);
1115                 }
1116                 for (std::vector<ZLine>::iterator i = pzlines.begin(); i != pzlines.end(); i++)
1117                 {
1118                         snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->ipaddr,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1119                         this->WriteLine(data);
1120                 }
1121                 for (std::vector<QLine>::iterator i = pqlines.begin(); i != pqlines.end(); i++)
1122                 {
1123                         snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->nick,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1124                         this->WriteLine(data);
1125                 }
1126                 for (std::vector<GLine>::iterator i = pglines.begin(); i != pglines.end(); i++)
1127                 {
1128                         snprintf(data,MAXBUF,":%s ADDLINE G %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1129                         this->WriteLine(data);
1130                 }
1131                 for (std::vector<ELine>::iterator i = pelines.begin(); i != pelines.end(); i++)
1132                 {
1133                         snprintf(data,MAXBUF,":%s ADDLINE E %s %s %lu %lu :%s",Srv->GetServerName().c_str(),i->hostmask,i->source,(unsigned long)i->set_time,(unsigned long)i->duration,i->reason);
1134                         this->WriteLine(data);
1135                 }
1136         }
1137
1138         /* Send channel modes and topics */
1139         void SendChannelModes(TreeServer* Current)
1140         {
1141                 char data[MAXBUF];
1142                 std::deque<std::string> list;
1143                 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
1144                 {
1145                         SendFJoins(Current, c->second);
1146                         snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
1147                         this->WriteLine(data);
1148                         if (*c->second->topic)
1149                         {
1150                                 snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",Srv->GetServerName().c_str(),c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
1151                                 this->WriteLine(data);
1152                         }
1153                         for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
1154                         {
1155                                 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
1156                                 this->WriteLine(data);
1157                         }
1158                         FOREACH_MOD(I_OnSyncChannel,OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this));
1159                         list.clear();
1160                         c->second->GetExtList(list);
1161                         for (unsigned int j = 0; j < list.size(); j++)
1162                         {
1163                                 FOREACH_MOD(I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
1164                         }
1165                 }
1166         }
1167
1168         /* send all users and their oper state/modes */
1169         void SendUsers(TreeServer* Current)
1170         {
1171                 char data[MAXBUF];
1172                 std::deque<std::string> list;
1173                 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
1174                 {
1175                         if (u->second->registered == 7)
1176                         {
1177                                 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->modes,u->second->ip,u->second->fullname);
1178                                 this->WriteLine(data);
1179                                 if (strchr(u->second->modes,'o'))
1180                                 {
1181                                         this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
1182                                 }
1183                                 FOREACH_MOD(I_OnSyncUser,OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this));
1184                                 list.clear();
1185                                 u->second->GetExtList(list);
1186                                 for (unsigned int j = 0; j < list.size(); j++)
1187                                 {
1188                                         FOREACH_MOD(I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)TreeProtocolModule,(void*)this,list[j]));
1189                                 }
1190                         }
1191                 }
1192         }
1193
1194         /* This function is called when we want to send a netburst to a local
1195          * server. There is a set order we must do this, because for example
1196          * users require their servers to exist, and channels require their
1197          * users to exist. You get the idea.
1198          */
1199         void DoBurst(TreeServer* s)
1200         {
1201                 Srv->SendOpers("*** Bursting to \2"+s->GetName()+"\2.");
1202                 this->WriteLine("BURST");
1203                 /* send our version string */
1204                 this->WriteLine(":"+Srv->GetServerName()+" VERSION :"+Srv->GetVersion());
1205                 /* Send server tree */
1206                 this->SendServers(TreeRoot,s,1);
1207                 /* Send users and their oper status */
1208                 this->SendUsers(s);
1209                 /* Send everything else (channel modes, xlines etc) */
1210                 this->SendChannelModes(s);
1211                 this->SendXLines(s);
1212                 this->WriteLine("ENDBURST");
1213                 Srv->SendOpers("*** Finished bursting to \2"+s->GetName()+"\2.");
1214         }
1215
1216         /* This function is called when we receive data from a remote
1217          * server. We buffer the data in a std::string (it doesnt stay
1218          * there for long), reading using InspSocket::Read() which can
1219          * read up to 16 kilobytes in one operation.
1220          *
1221          * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
1222          * THE SOCKET OBJECT FOR US.
1223          */
1224         virtual bool OnDataReady()
1225         {
1226                 char* data = this->Read();
1227                 if (data)
1228                 {
1229                         this->in_buffer += data;
1230                         /* While there is at least one new line in the buffer,
1231                          * do something useful (we hope!) with it.
1232                          */
1233                         while (in_buffer.find("\n") != std::string::npos)
1234                         {
1235                                 char* line = (char*)in_buffer.c_str();
1236                                 std::string ret = "";
1237                                 while ((*line != '\n') && (strlen(line)))
1238                                 {
1239                                         ret = ret + *line;
1240                                         line++;
1241                                 }
1242                                 if ((*line == '\n') || (*line == '\r'))
1243                                         line++;
1244                                 in_buffer = line;
1245                                 /* Process this one, abort if it
1246                                  * didnt return true.
1247                                  */
1248                                 if (this->ctx_in)
1249                                 {
1250                                         char out[1024];
1251                                         char result[1024];
1252                                         memset(result,0,1024);
1253                                         memset(out,0,1024);
1254                                         log(DEBUG,"Original string '%s'",ret.c_str());
1255                                         /* ERROR + CAPAB is still allowed unencryped */
1256                                         if ((ret.substr(0,7) != "ERROR :") && (ret.substr(0,6) != "CAPAB "))
1257                                         {
1258                                                 int nbytes = from64tobits(out, ret.c_str(), 1024);
1259                                                 if ((nbytes > 0) && (nbytes < 1024))
1260                                                 {
1261                                                         log(DEBUG,"m_spanningtree: decrypt %d bytes",nbytes);
1262                                                         ctx_in->Decrypt(out, result, nbytes, 1);
1263                                                         for (int t = 0; t < nbytes; t++)
1264                                                                 if (result[t] == '\7') result[t] = 0;
1265                                                         ret = result;
1266                                                 }
1267                                         }
1268                                 }
1269                                 if (!this->ProcessLine(ret))
1270                                 {
1271                                         return false;
1272                                 }
1273                         }
1274                 }
1275                 return (data != NULL);
1276         }
1277
1278         int WriteLine(std::string line)
1279         {
1280                 log(DEBUG,"OUT: %s",line.c_str());
1281                 if (this->ctx_out)
1282                 {
1283                         log(DEBUG,"AES context");
1284                         char result[10240];
1285                         char result64[10240];
1286                         if (this->keylength)
1287                         {
1288                                 while (line.length() % this->keylength != 0)
1289                                 {
1290                                         // pad it to be a multiple of the key length
1291                                         line = line + "\7";
1292                                 }
1293                         }
1294                         unsigned int ll = line.length();
1295                         log(DEBUG,"Plaintext line with padding = %d chars",ll);
1296                         ctx_out->Encrypt(line.c_str(), result, ll, 1);
1297                         log(DEBUG,"Encrypted.");
1298                         to64frombits((unsigned char*)result64,(unsigned char*)result,ll);
1299                         line = result64;
1300                         log(DEBUG,"Encrypted: %s",line.c_str());
1301                         //int from64tobits(char *out, const char *in, int maxlen);
1302                 }
1303                 return this->Write(line + "\r\n");
1304         }
1305
1306         /* Handle ERROR command */
1307         bool Error(std::deque<std::string> params)
1308         {
1309                 if (params.size() < 1)
1310                         return false;
1311                 std::string Errmsg = params[0];
1312                 std::string SName = myhost;
1313                 if (InboundServerName != "")
1314                 {
1315                         SName = InboundServerName;
1316                 }
1317                 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
1318                 /* we will return false to cause the socket to close.
1319                  */
1320                 return false;
1321         }
1322
1323         /* Because the core won't let users or even SERVERS set +o,
1324          * we use the OPERTYPE command to do this.
1325          */
1326         bool OperType(std::string prefix, std::deque<std::string> &params)
1327         {
1328                 if (params.size() != 1)
1329                         return true;
1330                 std::string opertype = params[0];
1331                 userrec* u = Srv->FindNick(prefix);
1332                 if (u)
1333                 {
1334                         strlcpy(u->oper,opertype.c_str(),NICKMAX);
1335                         if (!strchr(u->modes,'o'))
1336                         {
1337                                 strcat(u->modes,"o");
1338                         }
1339                         DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
1340                 }
1341                 return true;
1342         }
1343
1344         /* Because Andy insists that services-compatible servers must
1345          * implement SVSNICK and SVSJOIN, that's exactly what we do :p
1346          */
1347         bool ForceNick(std::string prefix, std::deque<std::string> &params)
1348         {
1349                 if (params.size() < 3)
1350                         return true;
1351                 userrec* u = Srv->FindNick(params[0]);
1352                 if (u)
1353                 {
1354                         Srv->ChangeUserNick(u,params[1]);
1355                         u->age = atoi(params[2].c_str());
1356                         DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
1357                 }
1358                 return true;
1359         }
1360
1361         bool ServiceJoin(std::string prefix, std::deque<std::string> &params)
1362         {
1363                 if (params.size() < 2)
1364                         return true;
1365                 userrec* u = Srv->FindNick(params[0]);
1366                 if (u)
1367                 {
1368                         Srv->JoinUserToChannel(u,params[1],"");
1369                         DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
1370                 }
1371                 return true;
1372         }
1373
1374         bool RemoteRehash(std::string prefix, std::deque<std::string> &params)
1375         {
1376                 if (params.size() < 1)
1377                         return false;
1378                 std::string servermask = params[0];
1379                 if (Srv->MatchText(Srv->GetServerName(),servermask))
1380                 {
1381                         Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
1382                         Srv->RehashServer();
1383                         ReadConfiguration(false);
1384                 }
1385                 DoOneToAllButSender(prefix,"REHASH",params,prefix);
1386                 return true;
1387         }
1388
1389         bool RemoteKill(std::string prefix, std::deque<std::string> &params)
1390         {
1391                 if (params.size() != 2)
1392                         return true;
1393                 std::string nick = params[0];
1394                 userrec* u = Srv->FindNick(prefix);
1395                 userrec* who = Srv->FindNick(nick);
1396                 if (who)
1397                 {
1398                         /* Prepend kill source, if we don't have one */
1399                         std::string sourceserv = prefix;
1400                         if (u)
1401                         {
1402                                 sourceserv = u->server;
1403                         }
1404                         if (*(params[1].c_str()) != '[')
1405                         {
1406                                 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
1407                         }
1408                         std::string reason = params[1];
1409                         params[1] = ":" + params[1];
1410                         DoOneToAllButSender(prefix,"KILL",params,sourceserv);
1411                         Srv->QuitUser(who,reason);
1412                 }
1413                 return true;
1414         }
1415
1416         bool LocalPong(std::string prefix, std::deque<std::string> &params)
1417         {
1418                 if (params.size() < 1)
1419                         return true;
1420                 TreeServer* ServerSource = FindServer(prefix);
1421                 if (ServerSource)
1422                 {
1423                         ServerSource->SetPingFlag();
1424                 }
1425                 return true;
1426         }
1427         
1428         bool MetaData(std::string prefix, std::deque<std::string> &params)
1429         {
1430                 if (params.size() < 3)
1431                         return true;
1432                 TreeServer* ServerSource = FindServer(prefix);
1433                 if (ServerSource)
1434                 {
1435                         if (*(params[0].c_str()) == '#')
1436                         {
1437                                 chanrec* c = Srv->FindChannel(params[0]);
1438                                 if (c)
1439                                 {
1440                                         FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
1441                                 }
1442                         }
1443                         else
1444                         {
1445                                 userrec* u = Srv->FindNick(params[0]);
1446                                 if (u)
1447                                 {
1448                                         FOREACH_MOD(I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
1449                                 }
1450                         }
1451                 }
1452                 params[2] = ":" + params[2];
1453                 DoOneToAllButSender(prefix,"METADATA",params,prefix);
1454                 return true;
1455         }
1456
1457         bool ServerVersion(std::string prefix, std::deque<std::string> &params)
1458         {
1459                 if (params.size() < 1)
1460                         return true;
1461                 TreeServer* ServerSource = FindServer(prefix);
1462                 if (ServerSource)
1463                 {
1464                         ServerSource->SetVersion(params[0]);
1465                 }
1466                 params[0] = ":" + params[0];
1467                 DoOneToAllButSender(prefix,"VERSION",params,prefix);
1468                 return true;
1469         }
1470
1471         bool ChangeHost(std::string prefix, std::deque<std::string> &params)
1472         {
1473                 if (params.size() < 1)
1474                         return true;
1475                 userrec* u = Srv->FindNick(prefix);
1476                 if (u)
1477                 {
1478                         Srv->ChangeHost(u,params[0]);
1479                         DoOneToAllButSender(prefix,"FHOST",params,u->server);
1480                 }
1481                 return true;
1482         }
1483
1484         bool AddLine(std::string prefix, std::deque<std::string> &params)
1485         {
1486                 if (params.size() < 6)
1487                         return true;
1488                 std::string linetype = params[0]; /* Z, Q, E, G, K */
1489                 std::string mask = params[1]; /* Line type dependent */
1490                 std::string source = params[2]; /* may not be online or may be a server */
1491                 std::string settime = params[3]; /* EPOCH time set */
1492                 std::string duration = params[4]; /* Duration secs */
1493                 std::string reason = params[5];
1494
1495                 switch (*(linetype.c_str()))
1496                 {
1497                         case 'Z':
1498                                 add_zline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1499                                 zline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1500                         break;
1501                         case 'Q':
1502                                 add_qline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1503                                 qline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1504                         break;
1505                         case 'E':
1506                                 add_eline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1507                                 eline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1508                         break;
1509                         case 'G':
1510                                 add_gline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1511                                 gline_set_creation_time((char*)mask.c_str(), atoi(settime.c_str()));
1512                         break;
1513                         case 'K':
1514                                 add_kline(atoi(duration.c_str()), source.c_str(), reason.c_str(), mask.c_str());
1515                         break;
1516                         default:
1517                                 /* Just in case... */
1518                                 Srv->SendOpers("*** \2WARNING\2: Invalid xline type '"+linetype+"' sent by server "+prefix+", ignored!");
1519                         break;
1520                 }
1521                 /* Send it on its way */
1522                 params[5] = ":" + params[5];
1523                 DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
1524                 return true;
1525         }
1526
1527         bool ChangeName(std::string prefix, std::deque<std::string> &params)
1528         {
1529                 if (params.size() < 1)
1530                         return true;
1531                 userrec* u = Srv->FindNick(prefix);
1532                 if (u)
1533                 {
1534                         Srv->ChangeGECOS(u,params[0]);
1535                         params[0] = ":" + params[0];
1536                         DoOneToAllButSender(prefix,"FNAME",params,u->server);
1537                 }
1538                 return true;
1539         }
1540
1541         bool Whois(std::string prefix, std::deque<std::string> &params)
1542         {
1543                 if (params.size() < 1)
1544                         return true;
1545                 log(DEBUG,"In IDLE command");
1546                 userrec* u = Srv->FindNick(prefix);
1547                 if (u)
1548                 {
1549                         log(DEBUG,"USER EXISTS: %s",u->nick);
1550                         // an incoming request
1551                         if (params.size() == 1)
1552                         {
1553                                 userrec* x = Srv->FindNick(params[0]);
1554                                 if (x->fd > -1)
1555                                 {
1556                                         userrec* x = Srv->FindNick(params[0]);
1557                                         log(DEBUG,"Got IDLE");
1558                                         char signon[MAXBUF];
1559                                         char idle[MAXBUF];
1560                                         log(DEBUG,"Sending back IDLE 3");
1561                                         snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
1562                                         snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-time(NULL)));
1563                                         std::deque<std::string> par;
1564                                         par.push_back(prefix);
1565                                         par.push_back(signon);
1566                                         par.push_back(idle);
1567                                         // ours, we're done, pass it BACK
1568                                         DoOneToOne(params[0],"IDLE",par,u->server);
1569                                 }
1570                                 else
1571                                 {
1572                                         // not ours pass it on
1573                                         DoOneToOne(prefix,"IDLE",params,x->server);
1574                                 }
1575                         }
1576                         else if (params.size() == 3)
1577                         {
1578                                 std::string who_did_the_whois = params[0];
1579                                 userrec* who_to_send_to = Srv->FindNick(who_did_the_whois);
1580                                 if (who_to_send_to->fd > -1)
1581                                 {
1582                                         log(DEBUG,"Got final IDLE");
1583                                         // an incoming reply to a whois we sent out
1584                                         std::string nick_whoised = prefix;
1585                                         unsigned long signon = atoi(params[1].c_str());
1586                                         unsigned long idle = atoi(params[2].c_str());
1587                                         if ((who_to_send_to) && (who_to_send_to->fd > -1))
1588                                                 do_whois(who_to_send_to,u,signon,idle,(char*)nick_whoised.c_str());
1589                                 }
1590                                 else
1591                                 {
1592                                         // not ours, pass it on
1593                                         DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
1594                                 }
1595                         }
1596                 }
1597                 return true;
1598         }
1599         
1600         bool LocalPing(std::string prefix, std::deque<std::string> &params)
1601         {
1602                 if (params.size() < 1)
1603                         return true;
1604                 std::string stufftobounce = params[0];
1605                 this->WriteLine(":"+Srv->GetServerName()+" PONG "+stufftobounce);
1606                 return true;
1607         }
1608
1609         bool RemoteServer(std::string prefix, std::deque<std::string> &params)
1610         {
1611                 if (params.size() < 4)
1612                         return false;
1613                 std::string servername = params[0];
1614                 std::string password = params[1];
1615                 // hopcount is not used for a remote server, we calculate this ourselves
1616                 std::string description = params[3];
1617                 TreeServer* ParentOfThis = FindServer(prefix);
1618                 if (!ParentOfThis)
1619                 {
1620                         this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
1621                         return false;
1622                 }
1623                 TreeServer* CheckDupe = FindServer(servername);
1624                 if (CheckDupe)
1625                 {
1626                         this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1627                         Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1628                         return false;
1629                 }
1630                 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
1631                 ParentOfThis->AddChild(Node);
1632                 params[3] = ":" + params[3];
1633                 DoOneToAllButSender(prefix,"SERVER",params,prefix);
1634                 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
1635                 return true;
1636         }
1637
1638         bool Outbound_Reply_Server(std::deque<std::string> &params)
1639         {
1640                 if (params.size() < 4)
1641                         return false;
1642                 std::string servername = params[0];
1643                 std::string password = params[1];
1644                 int hops = atoi(params[2].c_str());
1645                 if (hops)
1646                 {
1647                         this->WriteLine("ERROR :Server too far away for authentication");
1648                         Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, server is too far away for authentication");
1649                         return false;
1650                 }
1651                 std::string description = params[3];
1652                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1653                 {
1654                         if ((x->Name == servername) && (x->RecvPass == password))
1655                         {
1656                                 TreeServer* CheckDupe = FindServer(servername);
1657                                 if (CheckDupe)
1658                                 {
1659                                         this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1660                                         Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1661                                         return false;
1662                                 }
1663                                 // Begin the sync here. this kickstarts the
1664                                 // other side, waiting in WAIT_AUTH_2 state,
1665                                 // into starting their burst, as it shows
1666                                 // that we're happy.
1667                                 this->LinkState = CONNECTED;
1668                                 // we should add the details of this server now
1669                                 // to the servers tree, as a child of the root
1670                                 // node.
1671                                 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
1672                                 TreeRoot->AddChild(Node);
1673                                 params[3] = ":" + params[3];
1674                                 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
1675                                 this->bursting = true;
1676                                 this->DoBurst(Node);
1677                                 return true;
1678                         }
1679                 }
1680                 this->WriteLine("ERROR :Invalid credentials");
1681                 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, invalid link credentials");
1682                 return false;
1683         }
1684
1685         bool Inbound_Server(std::deque<std::string> &params)
1686         {
1687                 if (params.size() < 4)
1688                         return false;
1689                 std::string servername = params[0];
1690                 std::string password = params[1];
1691                 int hops = atoi(params[2].c_str());
1692                 if (hops)
1693                 {
1694                         this->WriteLine("ERROR :Server too far away for authentication");
1695                         Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, server is too far away for authentication");
1696                         return false;
1697                 }
1698                 std::string description = params[3];
1699                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1700                 {
1701                         if ((x->Name == servername) && (x->RecvPass == password))
1702                         {
1703                                 TreeServer* CheckDupe = FindServer(servername);
1704                                 if (CheckDupe)
1705                                 {
1706                                         this->WriteLine("ERROR :Server "+servername+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
1707                                         Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
1708                                         return false;
1709                                 }
1710                                 /* If the config says this link is encrypted, but the remote side
1711                                  * hasnt bothered to send the AES command before SERVER, then we
1712                                  * boot them off as we MUST have this connection encrypted.
1713                                  */
1714                                 if ((x->EncryptionKey != "") && (!this->ctx_in))
1715                                 {
1716                                         this->WriteLine("ERROR :This link requires AES encryption to be enabled. Plaintext connection refused.");
1717                                         Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, remote server did not enable AES.");
1718                                         return false;
1719                                 }
1720                                 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
1721                                 this->InboundServerName = servername;
1722                                 this->InboundDescription = description;
1723                                 // this is good. Send our details: Our server name and description and hopcount of 0,
1724                                 // along with the sendpass from this block.
1725                                 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
1726                                 // move to the next state, we are now waiting for THEM.
1727                                 this->LinkState = WAIT_AUTH_2;
1728                                 return true;
1729                         }
1730                 }
1731                 this->WriteLine("ERROR :Invalid credentials");
1732                 Srv->SendOpers("*** Server connection from \2"+servername+"\2 denied, invalid link credentials");
1733                 return false;
1734         }
1735
1736         void Split(std::string line, bool stripcolon, std::deque<std::string> &n)
1737         {
1738                 if (!strchr(line.c_str(),' '))
1739                 {
1740                         n.push_back(line);
1741                         return;
1742                 }
1743                 std::stringstream s(line);
1744                 std::string param = "";
1745                 n.clear();
1746                 int item = 0;
1747                 while (!s.eof())
1748                 {
1749                         char c;
1750                         s.get(c);
1751                         if (c == ' ')
1752                         {
1753                                 n.push_back(param);
1754                                 param = "";
1755                                 item++;
1756                         }
1757                         else
1758                         {
1759                                 if (!s.eof())
1760                                 {
1761                                         param = param + c;
1762                                 }
1763                                 if ((param == ":") && (item > 0))
1764                                 {
1765                                         param = "";
1766                                         while (!s.eof())
1767                                         {
1768                                                 s.get(c);
1769                                                 if (!s.eof())
1770                                                 {
1771                                                         param = param + c;
1772                                                 }
1773                                         }
1774                                         n.push_back(param);
1775                                         param = "";
1776                                 }
1777                         }
1778                 }
1779                 if (param != "")
1780                 {
1781                         n.push_back(param);
1782                 }
1783                 return;
1784         }
1785
1786         bool ProcessLine(std::string line)
1787         {
1788                 char* l = (char*)line.c_str();
1789                 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
1790                         l[strlen(l)-1] = '\0';
1791                 line = l;
1792                 if (line == "")
1793                         return true;
1794                 Srv->Log(DEBUG,"IN: "+line);
1795                 std::deque<std::string> params;
1796                 this->Split(line,true,params);
1797                 std::string command = "";
1798                 std::string prefix = "";
1799                 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
1800                 {
1801                         prefix = params[0];
1802                         command = params[1];
1803                         char* pref = (char*)prefix.c_str();
1804                         prefix = ++pref;
1805                         params.pop_front();
1806                         params.pop_front();
1807                 }
1808                 else
1809                 {
1810                         prefix = "";
1811                         command = params[0];
1812                         params.pop_front();
1813                 }
1814
1815                 if ((!this->ctx_in) && (command == "AES"))
1816                 {
1817                         std::string sserv = params[0];
1818                         for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1819                         {
1820                                 if ((x->EncryptionKey != "") && (x->Name == sserv))
1821                                 {
1822                                         this->InitAES(x->EncryptionKey,sserv);
1823                                 }
1824                         }
1825                         return true;
1826                 }
1827                 else if ((this->ctx_in) && (command == "AES"))
1828                 {
1829                         WriteOpers("*** \2AES\2: Encryption already enabled on this connection yet %s is trying to enable it twice!",params[0].c_str());
1830                 }
1831
1832                 switch (this->LinkState)
1833                 {
1834                         TreeServer* Node;
1835                         
1836                         case WAIT_AUTH_1:
1837                                 // Waiting for SERVER command from remote server. Server initiating
1838                                 // the connection sends the first SERVER command, listening server
1839                                 // replies with theirs if its happy, then if the initiator is happy,
1840                                 // it starts to send its net sync, which starts the merge, otherwise
1841                                 // it sends an ERROR.
1842                                 if (command == "PASS")
1843                                 {
1844                                         /* Silently ignored */
1845                                 }
1846                                 else if (command == "SERVER")
1847                                 {
1848                                         return this->Inbound_Server(params);
1849                                 }
1850                                 else if (command == "ERROR")
1851                                 {
1852                                         return this->Error(params);
1853                                 }
1854                                 else if (command == "USER")
1855                                 {
1856                                         this->WriteLine("ERROR :Client connections to this port are prohibited.");
1857                                         return false;
1858                                 }
1859                                 else if (command == "CAPAB")
1860                                 {
1861                                         return this->Capab(params);
1862                                 }
1863                                 else
1864                                 {
1865                                         this->WriteLine("ERROR :Invalid command in negotiation phase.");
1866                                         return false;
1867                                 }
1868                         break;
1869                         case WAIT_AUTH_2:
1870                                 // Waiting for start of other side's netmerge to say they liked our
1871                                 // password.
1872                                 if (command == "SERVER")
1873                                 {
1874                                         // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1875                                         // silently ignore.
1876                                         return true;
1877                                 }
1878                                 else if (command == "BURST")
1879                                 {
1880                                         this->LinkState = CONNECTED;
1881                                         Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
1882                                         TreeRoot->AddChild(Node);
1883                                         params.clear();
1884                                         params.push_back(InboundServerName);
1885                                         params.push_back("*");
1886                                         params.push_back("1");
1887                                         params.push_back(":"+InboundDescription);
1888                                         DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
1889                                         this->bursting = true;
1890                                         this->DoBurst(Node);
1891                                 }
1892                                 else if (command == "ERROR")
1893                                 {
1894                                         return this->Error(params);
1895                                 }
1896                                 else if (command == "CAPAB")
1897                                 {
1898                                         return this->Capab(params);
1899                                 }
1900                                 
1901                         break;
1902                         case LISTENER:
1903                                 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
1904                                 return false;
1905                         break;
1906                         case CONNECTING:
1907                                 if (command == "SERVER")
1908                                 {
1909                                         // another server we connected to, which was in WAIT_AUTH_1 state,
1910                                         // has just sent us their credentials. If we get this far, theyre
1911                                         // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1912                                         // if we're happy with this, we should send our netburst which
1913                                         // kickstarts the merge.
1914                                         return this->Outbound_Reply_Server(params);
1915                                 }
1916                                 else if (command == "ERROR")
1917                                 {
1918                                         return this->Error(params);
1919                                 }
1920                         break;
1921                         case CONNECTED:
1922                                 // This is the 'authenticated' state, when all passwords
1923                                 // have been exchanged and anything past this point is taken
1924                                 // as gospel.
1925                                 
1926                                 if (prefix != "")
1927                                 {
1928                                         std::string direction = prefix;
1929                                         userrec* t = Srv->FindNick(prefix);
1930                                         if (t)
1931                                         {
1932                                                 direction = t->server;
1933                                         }
1934                                         TreeServer* route_back_again = BestRouteTo(direction);
1935                                         if ((!route_back_again) || (route_back_again->GetSocket() != this))
1936                                         {
1937                                                 if (route_back_again)
1938                                                         log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
1939                                                 return true;
1940                                         }
1941                                 }
1942                                 
1943                                 if (command == "SVSMODE")
1944                                 {
1945                                         /* Services expects us to implement
1946                                          * SVSMODE. In inspircd its the same as
1947                                          * MODE anyway.
1948                                          */
1949                                         command = "MODE";
1950                                 }
1951                                 std::string target = "";
1952                                 /* Yes, know, this is a mess. Its reasonably fast though as we're
1953                                  * working with std::string here.
1954                                  */
1955                                 if ((command == "NICK") && (params.size() > 1))
1956                                 {
1957                                         return this->IntroduceClient(prefix,params);
1958                                 }
1959                                 else if (command == "FJOIN")
1960                                 {
1961                                         return this->ForceJoin(prefix,params);
1962                                 }
1963                                 else if (command == "SERVER")
1964                                 {
1965                                         return this->RemoteServer(prefix,params);
1966                                 }
1967                                 else if (command == "ERROR")
1968                                 {
1969                                         return this->Error(params);
1970                                 }
1971                                 else if (command == "OPERTYPE")
1972                                 {
1973                                         return this->OperType(prefix,params);
1974                                 }
1975                                 else if (command == "FMODE")
1976                                 {
1977                                         return this->ForceMode(prefix,params);
1978                                 }
1979                                 else if (command == "KILL")
1980                                 {
1981                                         return this->RemoteKill(prefix,params);
1982                                 }
1983                                 else if (command == "FTOPIC")
1984                                 {
1985                                         return this->ForceTopic(prefix,params);
1986                                 }
1987                                 else if (command == "REHASH")
1988                                 {
1989                                         return this->RemoteRehash(prefix,params);
1990                                 }
1991                                 else if (command == "METADATA")
1992                                 {
1993                                         return this->MetaData(prefix,params);
1994                                 }
1995                                 else if (command == "PING")
1996                                 {
1997                                         return this->LocalPing(prefix,params);
1998                                 }
1999                                 else if (command == "PONG")
2000                                 {
2001                                         return this->LocalPong(prefix,params);
2002                                 }
2003                                 else if (command == "VERSION")
2004                                 {
2005                                         return this->ServerVersion(prefix,params);
2006                                 }
2007                                 else if (command == "FHOST")
2008                                 {
2009                                         return this->ChangeHost(prefix,params);
2010                                 }
2011                                 else if (command == "FNAME")
2012                                 {
2013                                         return this->ChangeName(prefix,params);
2014                                 }
2015                                 else if (command == "ADDLINE")
2016                                 {
2017                                         return this->AddLine(prefix,params);
2018                                 }
2019                                 else if (command == "SVSNICK")
2020                                 {
2021                                         if (prefix == "")
2022                                         {
2023                                                 prefix = this->GetName();
2024                                         }
2025                                         return this->ForceNick(prefix,params);
2026                                 }
2027                                 else if (command == "IDLE")
2028                                 {
2029                                         return this->Whois(prefix,params);
2030                                 }
2031                                 else if (command == "SVSJOIN")
2032                                 {
2033                                         if (prefix == "")
2034                                         {
2035                                                 prefix = this->GetName();
2036                                         }
2037                                         return this->ServiceJoin(prefix,params);
2038                                 }
2039                                 else if (command == "SQUIT")
2040                                 {
2041                                         if (params.size() == 2)
2042                                         {
2043                                                 this->Squit(FindServer(params[0]),params[1]);
2044                                         }
2045                                         return true;
2046                                 }
2047                                 else if (command == "ENDBURST")
2048                                 {
2049                                         this->bursting = false;
2050                                         return true;
2051                                 }
2052                                 else
2053                                 {
2054                                         // not a special inter-server command.
2055                                         // Emulate the actual user doing the command,
2056                                         // this saves us having a huge ugly parser.
2057                                         userrec* who = Srv->FindNick(prefix);
2058                                         std::string sourceserv = this->myhost;
2059                                         if (this->InboundServerName != "")
2060                                         {
2061                                                 sourceserv = this->InboundServerName;
2062                                         }
2063                                         if (who)
2064                                         {
2065                                                 // its a user
2066                                                 target = who->server;
2067                                                 char* strparams[127];
2068                                                 for (unsigned int q = 0; q < params.size(); q++)
2069                                                 {
2070                                                         strparams[q] = (char*)params[q].c_str();
2071                                                 }
2072                                                 Srv->CallCommandHandler(command, strparams, params.size(), who);
2073                                         }
2074                                         else
2075                                         {
2076                                                 // its not a user. Its either a server, or somethings screwed up.
2077                                                 if (IsServer(prefix))
2078                                                 {
2079                                                         target = Srv->GetServerName();
2080                                                 }
2081                                                 else
2082                                                 {
2083                                                         log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
2084                                                         return true;
2085                                                 }
2086                                         }
2087                                         return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
2088
2089                                 }
2090                                 return true;
2091                         break;
2092                 }
2093                 return true;
2094         }
2095
2096         virtual std::string GetName()
2097         {
2098                 std::string sourceserv = this->myhost;
2099                 if (this->InboundServerName != "")
2100                 {
2101                         sourceserv = this->InboundServerName;
2102                 }
2103                 return sourceserv;
2104         }
2105
2106         virtual void OnTimeout()
2107         {
2108                 if (this->LinkState == CONNECTING)
2109                 {
2110                         Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
2111                 }
2112         }
2113
2114         virtual void OnClose()
2115         {
2116                 // Connection closed.
2117                 // If the connection is fully up (state CONNECTED)
2118                 // then propogate a netsplit to all peers.
2119                 std::string quitserver = this->myhost;
2120                 if (this->InboundServerName != "")
2121                 {
2122                         quitserver = this->InboundServerName;
2123                 }
2124                 TreeServer* s = FindServer(quitserver);
2125                 if (s)
2126                 {
2127                         Squit(s,"Remote host closed the connection");
2128                 }
2129                 WriteOpers("Server '\2%s\2[%s]' closed the connection.",quitserver.c_str(),this->GetIP().c_str());
2130         }
2131
2132         virtual int OnIncomingConnection(int newsock, char* ip)
2133         {
2134                 TreeSocket* s = new TreeSocket(newsock, ip);
2135                 Srv->AddSocket(s);
2136                 return true;
2137         }
2138 };
2139
2140 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
2141 {
2142         for (unsigned int c = 0; c < list.size(); c++)
2143         {
2144                 if (list[c] == server)
2145                 {
2146                         return;
2147                 }
2148         }
2149         list.push_back(server);
2150 }
2151
2152 // returns a list of DIRECT servernames for a specific channel
2153 void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
2154 {
2155         std::vector<char*> *ulist = c->GetUsers();
2156         unsigned int ucount = ulist->size();
2157         for (unsigned int i = 0; i < ucount; i++)
2158         {
2159                 char* o = (*ulist)[i];
2160                 userrec* otheruser = (userrec*)o;
2161                 if (otheruser->fd < 0)
2162                 {
2163                         TreeServer* best = BestRouteTo(otheruser->server);
2164                         if (best)
2165                                 AddThisServer(best,list);
2166                 }
2167         }
2168         return;
2169 }
2170
2171 bool DoOneToAllButSenderRaw(std::string data, std::string omit, std::string prefix, std::string command, std::deque<std::string> &params)
2172 {
2173         TreeServer* omitroute = BestRouteTo(omit);
2174         if ((command == "NOTICE") || (command == "PRIVMSG"))
2175         {
2176                 if ((params.size() >= 2) && (*(params[0].c_str()) != '$'))
2177                 {
2178                         if (*(params[0].c_str()) != '#')
2179                         {
2180                                 // special routing for private messages/notices
2181                                 userrec* d = Srv->FindNick(params[0]);
2182                                 if (d)
2183                                 {
2184                                         std::deque<std::string> par;
2185                                         par.push_back(params[0]);
2186                                         par.push_back(":"+params[1]);
2187                                         DoOneToOne(prefix,command,par,d->server);
2188                                         return true;
2189                                 }
2190                         }
2191                         else
2192                         {
2193                                 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
2194                                 chanrec* c = Srv->FindChannel(params[0]);
2195                                 if (c)
2196                                 {
2197                                         std::deque<TreeServer*> list;
2198                                         GetListOfServersForChannel(c,list);
2199                                         log(DEBUG,"Got a list of %d servers",list.size());
2200                                         unsigned int lsize = list.size();
2201                                         for (unsigned int i = 0; i < lsize; i++)
2202                                         {
2203                                                 TreeSocket* Sock = list[i]->GetSocket();
2204                                                 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
2205                                                 {
2206                                                         log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
2207                                                         Sock->WriteLine(data);
2208                                                 }
2209                                         }
2210                                         return true;
2211                                 }
2212                         }
2213                 }
2214         }
2215         unsigned int items = TreeRoot->ChildCount();
2216         for (unsigned int x = 0; x < items; x++)
2217         {
2218                 TreeServer* Route = TreeRoot->GetChild(x);
2219                 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
2220                 {
2221                         TreeSocket* Sock = Route->GetSocket();
2222                         Sock->WriteLine(data);
2223                 }
2224         }
2225         return true;
2226 }
2227
2228 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> &params, std::string omit)
2229 {
2230         TreeServer* omitroute = BestRouteTo(omit);
2231         std::string FullLine = ":" + prefix + " " + command;
2232         unsigned int words = params.size();
2233         for (unsigned int x = 0; x < words; x++)
2234         {
2235                 FullLine = FullLine + " " + params[x];
2236         }
2237         unsigned int items = TreeRoot->ChildCount();
2238         for (unsigned int x = 0; x < items; x++)
2239         {
2240                 TreeServer* Route = TreeRoot->GetChild(x);
2241                 // Send the line IF:
2242                 // The route has a socket (its a direct connection)
2243                 // The route isnt the one to be omitted
2244                 // The route isnt the path to the one to be omitted
2245                 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
2246                 {
2247                         TreeSocket* Sock = Route->GetSocket();
2248                         Sock->WriteLine(FullLine);
2249                 }
2250         }
2251         return true;
2252 }
2253
2254 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> &params)
2255 {
2256         std::string FullLine = ":" + prefix + " " + command;
2257         unsigned int words = params.size();
2258         for (unsigned int x = 0; x < words; x++)
2259         {
2260                 FullLine = FullLine + " " + params[x];
2261         }
2262         unsigned int items = TreeRoot->ChildCount();
2263         for (unsigned int x = 0; x < items; x++)
2264         {
2265                 TreeServer* Route = TreeRoot->GetChild(x);
2266                 if (Route->GetSocket())
2267                 {
2268                         TreeSocket* Sock = Route->GetSocket();
2269                         Sock->WriteLine(FullLine);
2270                 }
2271         }
2272         return true;
2273 }
2274
2275 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> &params, std::string target)
2276 {
2277         TreeServer* Route = BestRouteTo(target);
2278         if (Route)
2279         {
2280                 std::string FullLine = ":" + prefix + " " + command;
2281                 unsigned int words = params.size();
2282                 for (unsigned int x = 0; x < words; x++)
2283                 {
2284                         FullLine = FullLine + " " + params[x];
2285                 }
2286                 if (Route->GetSocket())
2287                 {
2288                         TreeSocket* Sock = Route->GetSocket();
2289                         Sock->WriteLine(FullLine);
2290                 }
2291                 return true;
2292         }
2293         else
2294         {
2295                 return true;
2296         }
2297 }
2298
2299 std::vector<TreeSocket*> Bindings;
2300
2301 void ReadConfiguration(bool rebind)
2302 {
2303         Conf = new ConfigReader;
2304         if (rebind)
2305         {
2306                 for (int j =0; j < Conf->Enumerate("bind"); j++)
2307                 {
2308                         std::string Type = Conf->ReadValue("bind","type",j);
2309                         std::string IP = Conf->ReadValue("bind","address",j);
2310                         long Port = Conf->ReadInteger("bind","port",j,true);
2311                         if (Type == "servers")
2312                         {
2313                                 if (IP == "*")
2314                                 {
2315                                         IP = "";
2316                                 }
2317                                 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
2318                                 if (listener->GetState() == I_LISTENING)
2319                                 {
2320                                         Srv->AddSocket(listener);
2321                                         Bindings.push_back(listener);
2322                                 }
2323                                 else
2324                                 {
2325                                         log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
2326                                         listener->Close();
2327                                         delete listener;
2328                                 }
2329                         }
2330                 }
2331         }
2332         LinkBlocks.clear();
2333         for (int j =0; j < Conf->Enumerate("link"); j++)
2334         {
2335                 Link L;
2336                 L.Name = Conf->ReadValue("link","name",j);
2337                 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
2338                 L.Port = Conf->ReadInteger("link","port",j,true);
2339                 L.SendPass = Conf->ReadValue("link","sendpass",j);
2340                 L.RecvPass = Conf->ReadValue("link","recvpass",j);
2341                 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
2342                 L.EncryptionKey =  Conf->ReadValue("link","encryptionkey",j);
2343                 L.NextConnectTime = time(NULL) + L.AutoConnect;
2344                 /* Bugfix by brain, do not allow people to enter bad configurations */
2345                 if ((L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
2346                 {
2347                         LinkBlocks.push_back(L);
2348                         log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
2349                 }
2350                 else
2351                 {
2352                         log(DEFAULT,"m_spanningtree: Invalid configuration for server '%s', ignored!",L.Name.c_str());
2353                 }
2354         }
2355         delete Conf;
2356 }
2357
2358
2359 class ModuleSpanningTree : public Module
2360 {
2361         std::vector<TreeSocket*> Bindings;
2362         int line;
2363         int NumServers;
2364
2365  public:
2366
2367         ModuleSpanningTree(Server* Me)
2368                 : Module::Module(Me)
2369         {
2370                 Srv = Me;
2371                 Bindings.clear();
2372
2373                 // Create the root of the tree
2374                 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
2375
2376                 ReadConfiguration(true);
2377         }
2378
2379         void ShowLinks(TreeServer* Current, userrec* user, int hops)
2380         {
2381                 std::string Parent = TreeRoot->GetName();
2382                 if (Current->GetParent())
2383                 {
2384                         Parent = Current->GetParent()->GetName();
2385                 }
2386                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
2387                 {
2388                         ShowLinks(Current->GetChild(q),user,hops+1);
2389                 }
2390                 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
2391         }
2392
2393         int CountLocalServs()
2394         {
2395                 return TreeRoot->ChildCount();
2396         }
2397
2398         int CountServs()
2399         {
2400                 return serverlist.size();
2401         }
2402
2403         void HandleLinks(char** parameters, int pcnt, userrec* user)
2404         {
2405                 ShowLinks(TreeRoot,user,0);
2406                 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
2407                 return;
2408         }
2409
2410         void HandleLusers(char** parameters, int pcnt, userrec* user)
2411         {
2412                 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),this->CountServs());
2413                 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
2414                 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
2415                 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
2416                 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
2417                 return;
2418         }
2419
2420         // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
2421
2422         void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
2423         {
2424                 if (line < 128)
2425                 {
2426                         for (int t = 0; t < depth; t++)
2427                         {
2428                                 matrix[line][t] = ' ';
2429                         }
2430                         strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
2431                         line++;
2432                         for (unsigned int q = 0; q < Current->ChildCount(); q++)
2433                         {
2434                                 ShowMap(Current->GetChild(q),user,depth+2,matrix);
2435                         }
2436                 }
2437         }
2438
2439         // Ok, prepare to be confused.
2440         // After much mulling over how to approach this, it struck me that
2441         // the 'usual' way of doing a /MAP isnt the best way. Instead of
2442         // keeping track of a ton of ascii characters, and line by line
2443         // under recursion working out where to place them using multiplications
2444         // and divisons, we instead render the map onto a backplane of characters
2445         // (a character matrix), then draw the branches as a series of "L" shapes
2446         // from the nodes. This is not only friendlier on CPU it uses less stack.
2447
2448         void HandleMap(char** parameters, int pcnt, userrec* user)
2449         {
2450                 // This array represents a virtual screen which we will
2451                 // "scratch" draw to, as the console device of an irc
2452                 // client does not provide for a proper terminal.
2453                 char matrix[128][80];
2454                 for (unsigned int t = 0; t < 128; t++)
2455                 {
2456                         matrix[t][0] = '\0';
2457                 }
2458                 line = 0;
2459                 // The only recursive bit is called here.
2460                 ShowMap(TreeRoot,user,0,matrix);
2461                 // Process each line one by one. The algorithm has a limit of
2462                 // 128 servers (which is far more than a spanning tree should have
2463                 // anyway, so we're ok). This limit can be raised simply by making
2464                 // the character matrix deeper, 128 rows taking 10k of memory.
2465                 for (int l = 1; l < line; l++)
2466                 {
2467                         // scan across the line looking for the start of the
2468                         // servername (the recursive part of the algorithm has placed
2469                         // the servers at indented positions depending on what they
2470                         // are related to)
2471                         int first_nonspace = 0;
2472                         while (matrix[l][first_nonspace] == ' ')
2473                         {
2474                                 first_nonspace++;
2475                         }
2476                         first_nonspace--;
2477                         // Draw the `- (corner) section: this may be overwritten by
2478                         // another L shape passing along the same vertical pane, becoming
2479                         // a |- (branch) section instead.
2480                         matrix[l][first_nonspace] = '-';
2481                         matrix[l][first_nonspace-1] = '`';
2482                         int l2 = l - 1;
2483                         // Draw upwards until we hit the parent server, causing possibly
2484                         // other corners (`-) to become branches (|-)
2485                         while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
2486                         {
2487                                 matrix[l2][first_nonspace-1] = '|';
2488                                 l2--;
2489                         }
2490                 }
2491                 // dump the whole lot to the user. This is the easy bit, honest.
2492                 for (int t = 0; t < line; t++)
2493                 {
2494                         WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
2495                 }
2496                 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
2497                 return;
2498         }
2499
2500         int HandleSquit(char** parameters, int pcnt, userrec* user)
2501         {
2502                 TreeServer* s = FindServerMask(parameters[0]);
2503                 if (s)
2504                 {
2505                         if (s == TreeRoot)
2506                         {
2507                                  WriteServ(user->fd,"NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
2508                                 return 1;
2509                         }
2510                         TreeSocket* sock = s->GetSocket();
2511                         if (sock)
2512                         {
2513                                 log(DEBUG,"Splitting server %s",s->GetName().c_str());
2514                                 WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
2515                                 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
2516                                 sock->Close();
2517                         }
2518                         else
2519                         {
2520                                 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
2521                         }
2522                 }
2523                 else
2524                 {
2525                          WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
2526                 }
2527                 return 1;
2528         }
2529
2530         int HandleRemoteWhois(char** parameters, int pcnt, userrec* user)
2531         {
2532                 if ((user->fd > -1) && (pcnt > 1))
2533                 {
2534                         userrec* remote = Srv->FindNick(parameters[1]);
2535                         if ((remote) && (remote->fd < 0))
2536                         {
2537                                 std::deque<std::string> params;
2538                                 params.push_back(parameters[1]);
2539                                 DoOneToOne(user->nick,"IDLE",params,remote->server);
2540                                 return 1;
2541                         }
2542                         else if (!remote)
2543                         {
2544                                 WriteServ(user->fd,"401 %s %s :No such nick/channel",user->nick, parameters[1]);
2545                                 WriteServ(user->fd,"318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
2546                                 return 1;
2547                         }
2548                 }
2549                 return 0;
2550         }
2551
2552         void DoPingChecks(time_t curtime)
2553         {
2554                 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
2555                 {
2556                         TreeServer* serv = TreeRoot->GetChild(j);
2557                         TreeSocket* sock = serv->GetSocket();
2558                         if (sock)
2559                         {
2560                                 if (curtime >= serv->NextPingTime())
2561                                 {
2562                                         if (serv->AnsweredLastPing())
2563                                         {
2564                                                 sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
2565                                                 serv->SetNextPingTime(curtime + 60);
2566                                         }
2567                                         else
2568                                         {
2569                                                 // they didnt answer, boot them
2570                                                 WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
2571                                                 sock->Squit(serv,"Ping timeout");
2572                                                 sock->Close();
2573                                                 return;
2574                                         }
2575                                 }
2576                         }
2577                 }
2578         }
2579
2580         void AutoConnectServers(time_t curtime)
2581         {
2582                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2583                 {
2584                         if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
2585                         {
2586                                 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
2587                                 x->NextConnectTime = curtime + x->AutoConnect;
2588                                 TreeServer* CheckDupe = FindServer(x->Name);
2589                                 if (!CheckDupe)
2590                                 {
2591                                         // an autoconnected server is not connected. Check if its time to connect it
2592                                         WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
2593                                         TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2594                                         Srv->AddSocket(newsocket);
2595                                 }
2596                         }
2597                 }
2598         }
2599
2600         int HandleVersion(char** parameters, int pcnt, userrec* user)
2601         {
2602                 // we've already checked if pcnt > 0, so this is safe
2603                 TreeServer* found = FindServerMask(parameters[0]);
2604                 if (found)
2605                 {
2606                         std::string Version = found->GetVersion();
2607                         WriteServ(user->fd,"351 %s :%s",user->nick,Version.c_str());
2608                 }
2609                 else
2610                 {
2611                         WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
2612                 }
2613                 return 1;
2614         }
2615         
2616         int HandleConnect(char** parameters, int pcnt, userrec* user)
2617         {
2618                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
2619                 {
2620                         if (Srv->MatchText(x->Name.c_str(),parameters[0]))
2621                         {
2622                                 TreeServer* CheckDupe = FindServer(x->Name);
2623                                 if (!CheckDupe)
2624                                 {
2625                                         WriteServ(user->fd,"NOTICE %s :*** CONNECT: Connecting to server: \002%s\002 (%s:%d)",user->nick,x->Name.c_str(),x->IPAddr.c_str(),x->Port);
2626                                         TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
2627                                         Srv->AddSocket(newsocket);
2628                                         return 1;
2629                                 }
2630                                 else
2631                                 {
2632                                         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());
2633                                         return 1;
2634                                 }
2635                         }
2636                 }
2637                 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
2638                 return 1;
2639         }
2640
2641         virtual bool HandleStats(char ** parameters, int pcnt, userrec* user)
2642         {
2643                 if (*parameters[0] == 'c')
2644                 {
2645                         for (unsigned int i = 0; i < LinkBlocks.size(); i++)
2646                         {
2647                                 WriteServ(user->fd,"213 %s C *@%s * %s %d 0 %s",user->nick,LinkBlocks[i].IPAddr.c_str(),LinkBlocks[i].Name.c_str(),LinkBlocks[i].Port,(LinkBlocks[i].EncryptionKey != "" ? "es" : " s"));
2648                                 WriteServ(user->fd,"244 %s H * * %s",user->nick,LinkBlocks[i].Name.c_str());
2649                         }
2650                         WriteServ(user->fd,"219 %s %s :End of /STATS report",user->nick,parameters[0]);
2651                         WriteOpers("*** Notice: Stats '%s' requested by %s (%s@%s)",parameters[0],user->nick,user->ident,user->host);
2652                         return true;
2653                 }
2654                 return false;
2655         }
2656
2657         virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user, bool validated)
2658         {
2659                 /* If the command doesnt appear to be valid, we dont want to mess with it. */
2660                 if (!validated)
2661                         return 0;
2662
2663                 if (command == "CONNECT")
2664                 {
2665                         return this->HandleConnect(parameters,pcnt,user);
2666                 }
2667                 else if (command == "SQUIT")
2668                 {
2669                         return this->HandleSquit(parameters,pcnt,user);
2670                 }
2671                 else if (command == "STATS")
2672                 {
2673                         return this->HandleStats(parameters,pcnt,user);
2674                 }
2675                 else if (command == "MAP")
2676                 {
2677                         this->HandleMap(parameters,pcnt,user);
2678                         return 1;
2679                 }
2680                 else if (command == "LUSERS")
2681                 {
2682                         this->HandleLusers(parameters,pcnt,user);
2683                         return 1;
2684                 }
2685                 else if (command == "LINKS")
2686                 {
2687                         this->HandleLinks(parameters,pcnt,user);
2688                         return 1;
2689                 }
2690                 else if (command == "WHOIS")
2691                 {
2692                         if (pcnt > 1)
2693                         {
2694                                 // remote whois
2695                                 return this->HandleRemoteWhois(parameters,pcnt,user);
2696                         }
2697                 }
2698                 else if ((command == "VERSION") && (pcnt > 0))
2699                 {
2700                         this->HandleVersion(parameters,pcnt,user);
2701                         return 1;
2702                 }
2703                 else if (Srv->IsValidModuleCommand(command, pcnt, user))
2704                 {
2705                         // this bit of code cleverly routes all module commands
2706                         // to all remote severs *automatically* so that modules
2707                         // can just handle commands locally, without having
2708                         // to have any special provision in place for remote
2709                         // commands and linking protocols.
2710                         std::deque<std::string> params;
2711                         params.clear();
2712                         for (int j = 0; j < pcnt; j++)
2713                         {
2714                                 if (strchr(parameters[j],' '))
2715                                 {
2716                                         params.push_back(":" + std::string(parameters[j]));
2717                                 }
2718                                 else
2719                                 {
2720                                         params.push_back(std::string(parameters[j]));
2721                                 }
2722                         }
2723                         DoOneToMany(user->nick,command,params);
2724                 }
2725                 return 0;
2726         }
2727
2728         virtual void OnGetServerDescription(std::string servername,std::string &description)
2729         {
2730                 TreeServer* s = FindServer(servername);
2731                 if (s)
2732                 {
2733                         description = s->GetDesc();
2734                 }
2735         }
2736
2737         virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
2738         {
2739                 if (source->fd > -1)
2740                 {
2741                         std::deque<std::string> params;
2742                         params.push_back(dest->nick);
2743                         params.push_back(channel->name);
2744                         DoOneToMany(source->nick,"INVITE",params);
2745                 }
2746         }
2747
2748         virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
2749         {
2750                 std::deque<std::string> params;
2751                 params.push_back(chan->name);
2752                 params.push_back(":"+topic);
2753                 DoOneToMany(user->nick,"TOPIC",params);
2754         }
2755
2756         virtual void OnWallops(userrec* user, std::string text)
2757         {
2758                 if (user->fd > -1)
2759                 {
2760                         std::deque<std::string> params;
2761                         params.push_back(":"+text);
2762                         DoOneToMany(user->nick,"WALLOPS",params);
2763                 }
2764         }
2765
2766         virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
2767         {
2768                 if (target_type == TYPE_USER)
2769                 {
2770                         userrec* d = (userrec*)dest;
2771                         if ((d->fd < 0) && (user->fd > -1))
2772                         {
2773                                 std::deque<std::string> params;
2774                                 params.clear();
2775                                 params.push_back(d->nick);
2776                                 params.push_back(":"+text);
2777                                 DoOneToOne(user->nick,"NOTICE",params,d->server);
2778                         }
2779                 }
2780                 else
2781                 {
2782                         if (user->fd > -1)
2783                         {
2784                                 chanrec *c = (chanrec*)dest;
2785                                 std::deque<TreeServer*> list;
2786                                 GetListOfServersForChannel(c,list);
2787                                 unsigned int ucount = list.size();
2788                                 for (unsigned int i = 0; i < ucount; i++)
2789                                 {
2790                                         TreeSocket* Sock = list[i]->GetSocket();
2791                                         if (Sock)
2792                                                 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+std::string(c->name)+" :"+text);
2793                                 }
2794                         }
2795                 }
2796         }
2797
2798         virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
2799         {
2800                 if (target_type == TYPE_USER)
2801                 {
2802                         // route private messages which are targetted at clients only to the server
2803                         // which needs to receive them
2804                         userrec* d = (userrec*)dest;
2805                         if ((d->fd < 0) && (user->fd > -1))
2806                         {
2807                                 std::deque<std::string> params;
2808                                 params.clear();
2809                                 params.push_back(d->nick);
2810                                 params.push_back(":"+text);
2811                                 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
2812                         }
2813                 }
2814                 else
2815                 {
2816                         if (user->fd > -1)
2817                         {
2818                                 chanrec *c = (chanrec*)dest;
2819                                 std::deque<TreeServer*> list;
2820                                 GetListOfServersForChannel(c,list);
2821                                 unsigned int ucount = list.size();
2822                                 for (unsigned int i = 0; i < ucount; i++)
2823                                 {
2824                                         TreeSocket* Sock = list[i]->GetSocket();
2825                                         if (Sock)
2826                                                 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+std::string(c->name)+" :"+text);
2827                                 }
2828                         }
2829                 }
2830         }
2831
2832         virtual void OnBackgroundTimer(time_t curtime)
2833         {
2834                 AutoConnectServers(curtime);
2835                 DoPingChecks(curtime);
2836         }
2837
2838         virtual void OnUserJoin(userrec* user, chanrec* channel)
2839         {
2840                 // Only do this for local users
2841                 if (user->fd > -1)
2842                 {
2843                         std::deque<std::string> params;
2844                         params.clear();
2845                         params.push_back(channel->name);
2846                         if (*channel->key)
2847                         {
2848                                 // if the channel has a key, force the join by emulating the key.
2849                                 params.push_back(channel->key);
2850                         }
2851                         if (channel->GetUserCounter() > 1)
2852                         {
2853                                 // not the first in the channel
2854                                 DoOneToMany(user->nick,"JOIN",params);
2855                         }
2856                         else
2857                         {
2858                                 // first in the channel, set up their permissions
2859                                 // and the channel TS with FJOIN.
2860                                 char ts[24];
2861                                 snprintf(ts,24,"%lu",(unsigned long)channel->age);
2862                                 params.clear();
2863                                 params.push_back(channel->name);
2864                                 params.push_back(ts);
2865                                 params.push_back("@"+std::string(user->nick));
2866                                 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
2867                         }
2868                 }
2869         }
2870
2871         virtual void OnChangeHost(userrec* user, std::string newhost)
2872         {
2873                 // only occurs for local clients
2874                 if (user->registered != 7)
2875                         return;
2876                 std::deque<std::string> params;
2877                 params.push_back(newhost);
2878                 DoOneToMany(user->nick,"FHOST",params);
2879         }
2880
2881         virtual void OnChangeName(userrec* user, std::string gecos)
2882         {
2883                 // only occurs for local clients
2884                 if (user->registered != 7)
2885                         return;
2886                 std::deque<std::string> params;
2887                 params.push_back(gecos);
2888                 DoOneToMany(user->nick,"FNAME",params);
2889         }
2890
2891         virtual void OnUserPart(userrec* user, chanrec* channel)
2892         {
2893                 if (user->fd > -1)
2894                 {
2895                         std::deque<std::string> params;
2896                         params.push_back(channel->name);
2897                         DoOneToMany(user->nick,"PART",params);
2898                 }
2899         }
2900
2901         virtual void OnUserConnect(userrec* user)
2902         {
2903                 char agestr[MAXBUF];
2904                 if (user->fd > -1)
2905                 {
2906                         std::deque<std::string> params;
2907                         snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
2908                         params.push_back(agestr);
2909                         params.push_back(user->nick);
2910                         params.push_back(user->host);
2911                         params.push_back(user->dhost);
2912                         params.push_back(user->ident);
2913                         params.push_back("+"+std::string(user->modes));
2914                         params.push_back(user->ip);
2915                         params.push_back(":"+std::string(user->fullname));
2916                         DoOneToMany(Srv->GetServerName(),"NICK",params);
2917                 }
2918         }
2919
2920         virtual void OnUserQuit(userrec* user, std::string reason)
2921         {
2922                 if ((user->fd > -1) && (user->registered == 7))
2923                 {
2924                         std::deque<std::string> params;
2925                         params.push_back(":"+reason);
2926                         DoOneToMany(user->nick,"QUIT",params);
2927                 }
2928         }
2929
2930         virtual void OnUserPostNick(userrec* user, std::string oldnick)
2931         {
2932                 if (user->fd > -1)
2933                 {
2934                         std::deque<std::string> params;
2935                         params.push_back(user->nick);
2936                         DoOneToMany(oldnick,"NICK",params);
2937                 }
2938         }
2939
2940         virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
2941         {
2942                 if (source->fd > -1)
2943                 {
2944                         std::deque<std::string> params;
2945                         params.push_back(chan->name);
2946                         params.push_back(user->nick);
2947                         params.push_back(":"+reason);
2948                         DoOneToMany(source->nick,"KICK",params);
2949                 }
2950         }
2951
2952         virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
2953         {
2954                 std::deque<std::string> params;
2955                 params.push_back(dest->nick);
2956                 params.push_back(":"+reason);
2957                 DoOneToMany(source->nick,"KILL",params);
2958         }
2959
2960         virtual void OnRehash(std::string parameter)
2961         {
2962                 if (parameter != "")
2963                 {
2964                         std::deque<std::string> params;
2965                         params.push_back(parameter);
2966                         DoOneToMany(Srv->GetServerName(),"REHASH",params);
2967                         // check for self
2968                         if (Srv->MatchText(Srv->GetServerName(),parameter))
2969                         {
2970                                 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
2971                                 Srv->RehashServer();
2972                         }
2973                 }
2974                 ReadConfiguration(false);
2975         }
2976
2977         // note: the protocol does not allow direct umode +o except
2978         // via NICK with 8 params. sending OPERTYPE infers +o modechange
2979         // locally.
2980         virtual void OnOper(userrec* user, std::string opertype)
2981         {
2982                 if (user->fd > -1)
2983                 {
2984                         std::deque<std::string> params;
2985                         params.push_back(opertype);
2986                         DoOneToMany(user->nick,"OPERTYPE",params);
2987                 }
2988         }
2989
2990         void OnLine(userrec* source, std::string host, bool adding, char linetype, long duration, std::string reason)
2991         {
2992                 if (source->fd > -1)
2993                 {
2994                         char type[8];
2995                         snprintf(type,8,"%cLINE",linetype);
2996                         std::string stype = type;
2997                         if (adding)
2998                         {
2999                                 char sduration[MAXBUF];
3000                                 snprintf(sduration,MAXBUF,"%ld",duration);
3001                                 std::deque<std::string> params;
3002                                 params.push_back(host);
3003                                 params.push_back(sduration);
3004                                 params.push_back(":"+reason);
3005                                 DoOneToMany(source->nick,stype,params);
3006                         }
3007                         else
3008                         {
3009                                 std::deque<std::string> params;
3010                                 params.push_back(host);
3011                                 DoOneToMany(source->nick,stype,params);
3012                         }
3013                 }
3014         }
3015
3016         virtual void OnAddGLine(long duration, userrec* source, std::string reason, std::string hostmask)
3017         {
3018                 OnLine(source,hostmask,true,'G',duration,reason);
3019         }
3020         
3021         virtual void OnAddZLine(long duration, userrec* source, std::string reason, std::string ipmask)
3022         {
3023                 OnLine(source,ipmask,true,'Z',duration,reason);
3024         }
3025
3026         virtual void OnAddQLine(long duration, userrec* source, std::string reason, std::string nickmask)
3027         {
3028                 OnLine(source,nickmask,true,'Q',duration,reason);
3029         }
3030
3031         virtual void OnAddELine(long duration, userrec* source, std::string reason, std::string hostmask)
3032         {
3033                 OnLine(source,hostmask,true,'E',duration,reason);
3034         }
3035
3036         virtual void OnDelGLine(userrec* source, std::string hostmask)
3037         {
3038                 OnLine(source,hostmask,false,'G',0,"");
3039         }
3040
3041         virtual void OnDelZLine(userrec* source, std::string ipmask)
3042         {
3043                 OnLine(source,ipmask,false,'Z',0,"");
3044         }
3045
3046         virtual void OnDelQLine(userrec* source, std::string nickmask)
3047         {
3048                 OnLine(source,nickmask,false,'Q',0,"");
3049         }
3050
3051         virtual void OnDelELine(userrec* source, std::string hostmask)
3052         {
3053                 OnLine(source,hostmask,false,'E',0,"");
3054         }
3055
3056         virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
3057         {
3058                 if ((user->fd > -1) && (user->registered == 7))
3059                 {
3060                         if (target_type == TYPE_USER)
3061                         {
3062                                 userrec* u = (userrec*)dest;
3063                                 std::deque<std::string> params;
3064                                 params.push_back(u->nick);
3065                                 params.push_back(text);
3066                                 DoOneToMany(user->nick,"MODE",params);
3067                         }
3068                         else
3069                         {
3070                                 chanrec* c = (chanrec*)dest;
3071                                 std::deque<std::string> params;
3072                                 params.push_back(c->name);
3073                                 params.push_back(text);
3074                                 DoOneToMany(user->nick,"MODE",params);
3075                         }
3076                 }
3077         }
3078
3079         virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
3080         {
3081                 TreeSocket* s = (TreeSocket*)opaque;
3082                 if (target)
3083                 {
3084                         if (target_type == TYPE_USER)
3085                         {
3086                                 userrec* u = (userrec*)target;
3087                                 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
3088                         }
3089                         else
3090                         {
3091                                 chanrec* c = (chanrec*)target;
3092                                 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
3093                         }
3094                 }
3095         }
3096
3097         virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, std::string extname, std::string extdata)
3098         {
3099                 TreeSocket* s = (TreeSocket*)opaque;
3100                 if (target)
3101                 {
3102                         if (target_type == TYPE_USER)
3103                         {
3104                                 userrec* u = (userrec*)target;
3105                                 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+u->nick+" "+extname+" :"+extdata);
3106                         }
3107                         else
3108                         {
3109                                 chanrec* c = (chanrec*)target;
3110                                 s->WriteLine(":"+Srv->GetServerName()+" METADATA "+c->name+" "+extname+" :"+extdata);
3111                         }
3112                 }
3113         }
3114
3115         virtual ~ModuleSpanningTree()
3116         {
3117         }
3118
3119         virtual Version GetVersion()
3120         {
3121                 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
3122         }
3123
3124         void Implements(char* List)
3125         {
3126                 List[I_OnPreCommand] = List[I_OnGetServerDescription] = List[I_OnUserInvite] = List[I_OnPostLocalTopicChange] = 1;
3127                 List[I_OnWallops] = List[I_OnUserNotice] = List[I_OnUserMessage] = List[I_OnBackgroundTimer] = 1;
3128                 List[I_OnUserJoin] = List[I_OnChangeHost] = List[I_OnChangeName] = List[I_OnUserPart] = List[I_OnUserConnect] = 1;
3129                 List[I_OnUserQuit] = List[I_OnUserPostNick] = List[I_OnUserKick] = List[I_OnRemoteKill] = List[I_OnRehash] = 1;
3130                 List[I_OnOper] = List[I_OnAddGLine] = List[I_OnAddZLine] = List[I_OnAddQLine] = List[I_OnAddELine] = 1;
3131                 List[I_OnDelGLine] = List[I_OnDelZLine] = List[I_OnDelQLine] = List[I_OnDelELine] = List[I_ProtoSendMode] = List[I_OnMode] = 1;
3132                 List[I_ProtoSendMetaData] = 1;
3133         }
3134 };
3135
3136
3137 class ModuleSpanningTreeFactory : public ModuleFactory
3138 {
3139  public:
3140         ModuleSpanningTreeFactory()
3141         {
3142         }
3143         
3144         ~ModuleSpanningTreeFactory()
3145         {
3146         }
3147         
3148         virtual Module * CreateModule(Server* Me)
3149         {
3150                 TreeProtocolModule = new ModuleSpanningTree(Me);
3151                 return TreeProtocolModule;
3152         }
3153         
3154 };
3155
3156
3157 extern "C" void * init_module( void )
3158 {
3159         return new ModuleSpanningTreeFactory;
3160 }