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