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