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