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