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