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