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