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