]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree.cpp
Optimized routing, some O(n) stuff could easily be made 'n'.
[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 using namespace std;
18
19 #include <stdio.h>
20 #include <vector>
21 #include <deque>
22 #include "globals.h"
23 #include "inspircd_config.h"
24 #ifdef GCC3
25 #include <ext/hash_map>
26 #else
27 #include <hash_map>
28 #endif
29 #include "users.h"
30 #include "channels.h"
31 #include "modules.h"
32 #include "socket.h"
33 #include "helperfuncs.h"
34 #include "inspircd.h"
35 #include "inspstring.h"
36 #include "hashcomp.h"
37 #include "message.h"
38
39 #ifdef GCC3
40 #define nspace __gnu_cxx
41 #else
42 #define nspace std
43 #endif
44
45 class ModuleSpanningTree;
46 static ModuleSpanningTree* TreeProtocolModule;
47
48 extern std::vector<Module*> modules;
49 extern std::vector<ircd_module*> factory;
50 extern int MODCOUNT;
51
52 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
53
54 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
55 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;
56
57 extern user_hash clientlist;
58 extern chan_hash chanlist;
59
60 class TreeServer;
61 class TreeSocket;
62
63 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target);
64 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit);
65 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params);
66 bool DoOneToAllButSenderRaw(std::string data,std::string omit);
67
68 class TreeServer
69 {
70         TreeServer* Parent;
71         std::vector<TreeServer*> Children;
72         std::string ServerName;
73         std::string ServerDesc;
74         std::string VersionString;
75         int UserCount;
76         int OperCount;
77         TreeSocket* Socket;     // for directly connected servers this points at the socket object
78         
79  public:
80
81         TreeServer()
82         {
83                 Parent = NULL;
84                 ServerName = "";
85                 ServerDesc = "";
86                 VersionString = "";
87                 UserCount = OperCount = 0;
88         }
89
90         TreeServer(std::string Name, std::string Desc) : ServerName(Name), ServerDesc(Desc)
91         {
92                 Parent = NULL;
93                 VersionString = "";
94                 UserCount = OperCount = 0;
95         }
96
97         TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name), ServerDesc(Desc), Socket(Sock)
98         {
99                 VersionString = "";
100                 UserCount = OperCount = 0;
101         }
102
103         std::string GetName()
104         {
105                 return this->ServerName;
106         }
107
108         std::string GetDesc()
109         {
110                 return this->ServerDesc;
111         }
112
113         std::string GetVersion()
114         {
115                 return this->VersionString;
116         }
117
118         int GetUserCount()
119         {
120                 return this->UserCount;
121         }
122
123         int GetOperCount()
124         {
125                 return this->OperCount;
126         }
127
128         TreeSocket* GetSocket()
129         {
130                 return this->Socket;
131         }
132
133         TreeServer* GetParent()
134         {
135                 return this->Parent;
136         }
137
138         unsigned int ChildCount()
139         {
140                 return Children.size();
141         }
142
143         TreeServer* GetChild(unsigned int n)
144         {
145                 if (n < Children.size())
146                 {
147                         return Children[n];
148                 }
149                 else
150                 {
151                         return NULL;
152                 }
153         }
154
155         void AddChild(TreeServer* Child)
156         {
157                 Children.push_back(Child);
158         }
159
160         bool DelChild(TreeServer* Child)
161         {
162                 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
163                 {
164                         if (*a == Child)
165                         {
166                                 Children.erase(a);
167                                 return true;
168                         }
169                 }
170                 return false;
171         }
172
173         // removes child nodes of this node, and of that node, etc etc
174         bool Tidy()
175         {
176                 bool stillchildren = true;
177                 while (stillchildren)
178                 {
179                         stillchildren = false;
180                         for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
181                         {
182                                 TreeServer* s = (TreeServer*)*a;
183                                 s->Tidy();
184                                 Children.erase(a);
185                                 delete s;
186                                 stillchildren = true;
187                                 break;
188                         }
189                 }
190                 return true;
191         }
192 };
193
194 class Link
195 {
196  public:
197          std::string Name;
198          std::string IPAddr;
199          int Port;
200          std::string SendPass;
201          std::string RecvPass;
202 };
203
204 /* $ModDesc: Povides a spanning tree server link protocol */
205
206 Server *Srv;
207 ConfigReader *Conf;
208 TreeServer *TreeRoot;
209 std::vector<Link> LinkBlocks;
210
211 TreeServer* RouteEnumerate(TreeServer* Current, std::string ServerName)
212 {
213         if (Current->GetName() == ServerName)
214                 return Current;
215         for (unsigned int q = 0; q < Current->ChildCount(); q++)
216         {
217                 TreeServer* found = RouteEnumerate(Current->GetChild(q),ServerName);
218                 if (found)
219                 {
220                         return found;
221                 }
222         }
223         return NULL;
224 }
225
226 // Returns the locally connected server we must route a
227 // message through to reach server 'ServerName'. This
228 // only applies to one-to-one and not one-to-many routing.
229 TreeServer* BestRouteTo(std::string ServerName)
230 {
231         log(DEBUG,"Finding best route to %s",ServerName.c_str());
232         if (ServerName.c_str() == TreeRoot->GetName())
233         {
234                 log(DEBUG,"Cant route to myself!!!");
235                 return NULL;
236         }
237         // first, find the server by recursively walking the tree
238         TreeServer* Found = RouteEnumerate(TreeRoot,ServerName);
239         // did we find it? If not, they did something wrong, abort.
240         if (!Found)
241         {
242                 log(DEBUG,"Failed to find %s by walking tree!",ServerName.c_str());
243                 return NULL;
244         }
245         else
246         {
247                 // The server exists, follow its parent nodes until
248                 // the parent of the current is 'TreeRoot', we know
249                 // then that this is a directly-connected server.
250                 while ((Found) && (Found->GetParent() != TreeRoot))
251                 {
252                         Found = Found->GetParent();
253                 }
254                 log(DEBUG,"Route to %s is via %s",ServerName.c_str(),Found->GetName().c_str());
255                 return Found;
256         }
257 }
258
259 bool LookForServer(TreeServer* Current, std::string ServerName)
260 {
261         if (ServerName == Current->GetName())
262                 return true;
263         for (unsigned int q = 0; q < Current->ChildCount(); q++)
264         {
265                 if (LookForServer(Current->GetChild(q),ServerName))
266                         return true;
267         }
268         return false;
269 }
270
271 TreeServer* Found;
272
273 void RFindServer(TreeServer* Current, std::string ServerName)
274 {
275         if ((ServerName == Current->GetName()) && (!Found))
276         {
277                 Found = Current;
278                 log(DEBUG,"Found server %s desc %s",Current->GetName().c_str(),Current->GetDesc().c_str());
279                 return;
280         }
281         if (!Found)
282         {
283                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
284                 {
285                         if (!Found)
286                                 RFindServer(Current->GetChild(q),ServerName);
287                 }
288         }
289         return;
290 }
291
292 TreeServer* FindServer(std::string ServerName)
293 {
294         Found = NULL;
295         RFindServer(TreeRoot,ServerName);
296         return Found;
297 }
298
299 bool IsServer(std::string ServerName)
300 {
301         return LookForServer(TreeRoot,ServerName);
302 }
303
304 class TreeSocket : public InspSocket
305 {
306         std::string myhost;
307         std::string in_buffer;
308         ServerState LinkState;
309         std::string InboundServerName;
310         std::string InboundDescription;
311         int num_lost_users;
312         int num_lost_servers;
313         
314  public:
315
316         TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
317                 : InspSocket(host, port, listening, maxtime)
318         {
319                 Srv->Log(DEBUG,"Create new listening");
320                 myhost = host;
321                 this->LinkState = LISTENER;
322         }
323
324         TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
325                 : InspSocket(host, port, listening, maxtime)
326         {
327                 Srv->Log(DEBUG,"Create new outbound");
328                 myhost = ServerName;
329                 this->LinkState = CONNECTING;
330         }
331
332         TreeSocket(int newfd, char* ip)
333                 : InspSocket(newfd, ip)
334         {
335                 Srv->Log(DEBUG,"Associate new inbound");
336                 this->LinkState = WAIT_AUTH_1;
337         }
338         
339         virtual bool OnConnected()
340         {
341                 if (this->LinkState == CONNECTING)
342                 {
343                         Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
344                         // we should send our details here.
345                         // if the other side is satisfied, they send theirs.
346                         // we do not need to change state here.
347                         for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
348                         {
349                                 if (x->Name == this->myhost)
350                                 {
351                                         // found who we're supposed to be connecting to, send the neccessary gubbins.
352                                         this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
353                                         return true;
354                                 }
355                         }
356                 }
357                 log(DEBUG,"Outbound connection ERROR: Could not find the right link block!");
358                 return true;
359         }
360         
361         virtual void OnError(InspSocketError e)
362         {
363         }
364
365         virtual int OnDisconnect()
366         {
367                 return true;
368         }
369
370         // recursively send the server tree with distances as hops
371         void SendServers(TreeServer* Current, TreeServer* s, int hops)
372         {
373                 char command[1024];
374                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
375                 {
376                         TreeServer* recursive_server = Current->GetChild(q);
377                         if (recursive_server != s)
378                         {
379                                 // :source.server SERVER server.name hops :Description
380                                 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
381                                 this->WriteLine(command);
382                                 // down to next level
383                                 this->SendServers(recursive_server, s, hops+1);
384                         }
385                 }
386         }
387
388         void SquitServer(TreeServer* Current)
389         {
390                 // recursively squit the servers attached to 'Current'
391                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
392                 {
393                         TreeServer* recursive_server = Current->GetChild(q);
394                         this->SquitServer(recursive_server);
395                 }
396                 // Now we've whacked the kids, whack self
397                 log(DEBUG,"Deleted %s",Current->GetName().c_str());
398                 num_lost_servers++;
399                 bool quittingpeople = true;
400                 while (quittingpeople)
401                 {
402                         quittingpeople = false;
403                         for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
404                         {
405                                 if (!strcasecmp(u->second->server,Current->GetName().c_str()))
406                                 {
407                                         log(DEBUG,"Quitting user %s of server %s",u->second->nick,u->second->server);
408                                         Srv->QuitUser(u->second,Current->GetName()+" "+std::string(Srv->GetServerName()));
409                                         num_lost_users++;
410                                         quittingpeople = true;
411                                         break;
412                                 }
413                         }
414                 }
415         }
416
417         void Squit(TreeServer* Current,std::string reason)
418         {
419                 if (Current)
420                 {
421                         std::deque<std::string> params;
422                         params.push_back(Current->GetName());
423                         params.push_back(":"+reason);
424                         DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
425                         if (Current->GetParent() == TreeRoot)
426                         {
427                                 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
428                         }
429                         else
430                         {
431                                 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
432                         }
433                         num_lost_servers = 0;
434                         num_lost_users = 0;
435                         SquitServer(Current);
436                         Current->Tidy();
437                         Current->GetParent()->DelChild(Current);
438                         delete Current;
439                         WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
440                 }
441                 else
442                 {
443                         log(DEBUG,"Squit from unknown server");
444                 }
445         }
446
447         bool ForceMode(std::string source, std::deque<std::string> params)
448         {
449                 userrec* who = new userrec;
450                 who->fd = FD_MAGIC_NUMBER;
451                 if (params.size() < 2)
452                         return true;
453                 char* modelist[255];
454                 for (unsigned int q = 0; q < params.size(); q++)
455                 {
456                         modelist[q] = (char*)params[q].c_str();
457                 }
458                 Srv->SendMode(modelist,params.size(),who);
459                 DoOneToAllButSender(source,"FMODE",params,source);
460                 delete who;
461                 return true;
462         }
463
464         bool ForceTopic(std::string source, std::deque<std::string> params)
465         {
466                 // FTOPIC %s %lu %s :%s
467                 if (params.size() != 4)
468                         return true;
469                 std::string channel = params[0];
470                 time_t ts = atoi(params[1].c_str());
471                 std::string setby = params[2];
472                 std::string topic = params[3];
473
474                 chanrec* c = Srv->FindChannel(channel);
475                 if (c)
476                 {
477                         if ((ts >= c->topicset) || (!*c->topic))
478                         {
479                                 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
480                                 strlcpy(c->setby,setby.c_str(),NICKMAX);
481                                 c->topicset = ts;
482                                 WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
483                         }
484                         
485                 }
486                 
487                 // all done, send it on its way
488                 params[3] = ":" + params[3];
489                 DoOneToAllButSender(source,"FTOPIC",params,source);
490
491                 return true;
492         }
493
494         bool ForceJoin(std::string source, std::deque<std::string> params)
495         {
496                 if (params.size() < 1)
497                         return true;
498                 for (unsigned int channelnum = 0; channelnum < params.size(); channelnum++)
499                 {
500                         // process one channel at a time, applying modes.
501                         char* channel = (char*)params[channelnum].c_str();
502                         char permissions = *channel;
503                         char* mode = NULL;
504                         switch (permissions)
505                         {
506                                 case '@':
507                                         channel++;
508                                         mode = "+o";
509                                 break;
510                                 case '%':
511                                         channel++;
512                                         mode = "+h";
513                                 break;
514                                 case '+':
515                                         channel++;
516                                         mode = "+v";
517                                 break;
518                         }
519                         userrec* who = Srv->FindNick(source);
520                         if (who)
521                         {
522                                 char* key = "";
523                                 chanrec* chan = Srv->FindChannel(channel);
524                                 if ((chan) && (*chan->key))
525                                 {
526                                         key = chan->key;
527                                 }
528                                 Srv->JoinUserToChannel(who,channel,key);
529                                 if (mode)
530                                 {
531                                         char* modelist[3];
532                                         modelist[0] = channel;
533                                         modelist[1] = mode;
534                                         modelist[2] = who->nick;
535                                         Srv->SendMode(modelist,3,who);
536                                 }
537                                 DoOneToAllButSender(source,"FJOIN",params,who->server);
538                         }
539                 }
540                 return true;
541         }
542
543         bool IntroduceClient(std::string source, std::deque<std::string> params)
544         {
545                 if (params.size() < 8)
546                         return true;
547                 // NICK age nick host dhost ident +modes ip :gecos
548                 //       0   1    2    3      4     5    6   7
549                 std::string nick = params[1];
550                 std::string host = params[2];
551                 std::string dhost = params[3];
552                 std::string ident = params[4];
553                 time_t age = atoi(params[0].c_str());
554                 std::string modes = params[5];
555                 if (*(modes.c_str()) == '+')
556                 {
557                         char* m = (char*)modes.c_str();
558                         m++;
559                         modes = m;
560                 }
561                 std::string ip = params[6];
562                 std::string gecos = params[7];
563                 char* tempnick = (char*)nick.c_str();
564                 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
565                 
566                 user_hash::iterator iter;
567                 iter = clientlist.find(tempnick);
568                 if (iter != clientlist.end())
569                 {
570                         // nick collision
571                         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);
572                         this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
573                         return true;
574                 }
575
576                 clientlist[tempnick] = new userrec();
577                 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
578                 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
579                 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
580                 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
581                 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
582                 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
583                 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
584                 clientlist[tempnick]->registered = 7;
585                 clientlist[tempnick]->signon = age;
586                 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
587                 for (int i = 0; i < MAXCHANS; i++)
588                 {
589                         clientlist[tempnick]->chans[i].channel = NULL;
590                         clientlist[tempnick]->chans[i].uc_modes = 0;
591                 }
592                 params[7] = ":" + params[7];
593                 DoOneToAllButSender(source,"NICK",params,source);
594                 return true;
595         }
596
597         void SendChannelModes(TreeServer* Current)
598         {
599                 char data[MAXBUF];
600                 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
601                 {
602                         snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
603                         this->WriteLine(data);
604                         if (*c->second->topic)
605                         {
606                                 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);
607                                 this->WriteLine(data);
608                         }
609                         for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
610                         {
611                                 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
612                                 this->WriteLine(data);
613                         }
614                         FOREACH_MOD OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this);
615                 }
616         }
617
618         // send all users and their channels
619         void SendUsers(TreeServer* Current)
620         {
621                 char data[MAXBUF];
622                 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
623                 {
624                         if (u->second->registered == 7)
625                         {
626                                 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);
627                                 this->WriteLine(data);
628                                 if (strchr(u->second->modes,'o'))
629                                 {
630                                         this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
631                                 }
632                                 char* chl = chlist(u->second,u->second);
633                                 if (*chl)
634                                 {
635                                         this->WriteLine(":"+std::string(u->second->nick)+" FJOIN "+std::string(chl));
636                                 }
637                                 FOREACH_MOD OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this);
638                         }
639                 }
640         }
641
642         void DoBurst(TreeServer* s)
643         {
644                 log(DEBUG,"Beginning network burst");
645                 Srv->SendOpers("*** Bursting to "+s->GetName()+".");
646                 this->WriteLine("BURST");
647                 // Send server tree
648                 this->SendServers(TreeRoot,s,1);
649                 // Send users and their channels
650                 this->SendUsers(s);
651                 // TODO: Send everything else (channel modes etc)
652                 this->SendChannelModes(s);
653                 this->WriteLine("ENDBURST");
654         }
655
656         virtual bool OnDataReady()
657         {
658                 char* data = this->Read();
659                 if (data)
660                 {
661                         this->in_buffer += data;
662                         while (in_buffer.find("\n") != std::string::npos)
663                         {
664                                 char* line = (char*)in_buffer.c_str();
665                                 std::string ret = "";
666                                 while ((*line != '\n') && (strlen(line)))
667                                 {
668                                         ret = ret + *line;
669                                         line++;
670                                 }
671                                 if ((*line == '\n') || (*line == '\r'))
672                                         line++;
673                                 in_buffer = line;
674                                 if (!this->ProcessLine(ret))
675                                 {
676                                         return false;
677                                 }
678                         }
679                 }
680                 return (data != NULL);
681         }
682
683         int WriteLine(std::string line)
684         {
685                 return this->Write(line + "\r\n");
686         }
687
688         bool Error(std::deque<std::string> params)
689         {
690                 if (params.size() < 1)
691                         return false;
692                 std::string Errmsg = params[0];
693                 std::string SName = myhost;
694                 if (InboundServerName != "")
695                 {
696                         SName = InboundServerName;
697                 }
698                 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
699                 // we will return false to cause the socket to close.
700                 return false;
701         }
702
703         bool OperType(std::string prefix, std::deque<std::string> params)
704         {
705                 if (params.size() != 1)
706                         return true;
707                 std::string opertype = params[0];
708                 userrec* u = Srv->FindNick(prefix);
709                 if (u)
710                 {
711                         strlcpy(u->oper,opertype.c_str(),NICKMAX);
712                         if (!strchr(u->modes,'o'))
713                         {
714                                 strcat(u->modes,"o");
715                         }
716                         DoOneToAllButSender(u->server,"OPERTYPE",params,u->server);
717                 }
718                 return true;
719         }
720
721         bool RemoteRehash(std::string prefix, std::deque<std::string> params)
722         {
723                 if (params.size() < 1)
724                         return true;
725                 std::string servermask = params[0];
726                 if (Srv->MatchText(Srv->GetServerName(),servermask))
727                 {
728                         Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
729                         Srv->RehashServer();
730                 }
731                 DoOneToAllButSender(prefix,"REHASH",params,prefix);
732                 return true;
733         }
734
735         bool RemoteKill(std::string prefix, std::deque<std::string> params)
736         {
737                 if (params.size() != 2)
738                         return true;
739                 std::string nick = params[0];
740                 std::string reason = params[1];
741                 userrec* u = Srv->FindNick(prefix);
742                 userrec* who = Srv->FindNick(nick);
743                 if (who)
744                 {
745                         std::string sourceserv = prefix;
746                         if (u)
747                         {
748                                 sourceserv = u->server;
749                         }
750                         params[1] = ":" + params[1];
751                         DoOneToAllButSender(prefix,"KILL",params,sourceserv);
752                         Srv->QuitUser(who,reason);
753                 }
754                 return true;
755         }
756
757         bool RemoteServer(std::string prefix, std::deque<std::string> params)
758         {
759                 if (params.size() < 4)
760                         return false;
761                 std::string servername = params[0];
762                 std::string password = params[1];
763                 // hopcount is not used for a remote server, we calculate this ourselves
764                 std::string description = params[3];
765                 TreeServer* ParentOfThis = FindServer(prefix);
766                 if (!ParentOfThis)
767                 {
768                         this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
769                         return false;
770                 }
771                 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
772                 ParentOfThis->AddChild(Node);
773                 params[3] = ":" + params[3];
774                 DoOneToAllButSender(prefix,"SERVER",params,prefix);
775                 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
776                 return true;
777         }
778
779         bool Outbound_Reply_Server(std::deque<std::string> params)
780         {
781                 if (params.size() < 4)
782                         return false;
783                 std::string servername = params[0];
784                 std::string password = params[1];
785                 int hops = atoi(params[2].c_str());
786                 if (hops)
787                 {
788                         this->WriteLine("ERROR :Server too far away for authentication");
789                         return false;
790                 }
791                 std::string description = params[3];
792                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
793                 {
794                         if ((x->Name == servername) && (x->RecvPass == password))
795                         {
796                                 // Begin the sync here. this kickstarts the
797                                 // other side, waiting in WAIT_AUTH_2 state,
798                                 // into starting their burst, as it shows
799                                 // that we're happy.
800                                 this->LinkState = CONNECTED;
801                                 // we should add the details of this server now
802                                 // to the servers tree, as a child of the root
803                                 // node.
804                                 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
805                                 TreeRoot->AddChild(Node);
806                                 params[3] = ":" + params[3];
807                                 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
808                                 this->DoBurst(Node);
809                                 return true;
810                         }
811                 }
812                 this->WriteLine("ERROR :Invalid credentials");
813                 return false;
814         }
815
816         bool Inbound_Server(std::deque<std::string> params)
817         {
818                 if (params.size() < 4)
819                         return false;
820                 std::string servername = params[0];
821                 std::string password = params[1];
822                 int hops = atoi(params[2].c_str());
823                 if (hops)
824                 {
825                         this->WriteLine("ERROR :Server too far away for authentication");
826                         return false;
827                 }
828                 std::string description = params[3];
829                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
830                 {
831                         if ((x->Name == servername) && (x->RecvPass == password))
832                         {
833                                 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
834                                 this->InboundServerName = servername;
835                                 this->InboundDescription = description;
836                                 // this is good. Send our details: Our server name and description and hopcount of 0,
837                                 // along with the sendpass from this block.
838                                 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
839                                 // move to the next state, we are now waiting for THEM.
840                                 this->LinkState = WAIT_AUTH_2;
841                                 return true;
842                         }
843                 }
844                 this->WriteLine("ERROR :Invalid credentials");
845                 return false;
846         }
847
848         std::deque<std::string> Split(std::string line, bool stripcolon)
849         {
850                 std::deque<std::string> n;
851                 std::stringstream s(line);
852                 std::string param = "";
853                 n.clear();
854                 int item = 0;
855                 while (!s.eof())
856                 {
857                         s >> param;
858                         if ((param != "") && (param != "\n"))
859                         {
860                                 if ((param.c_str()[0] == ':') && (item))
861                                 {
862                                         char* str = (char*)param.c_str();
863                                         str++;
864                                         param = str;
865                                         std::string append;
866                                         while (!s.eof())
867                                         {
868                                                 append = "";
869                                                 s >> append;
870                                                 if (append != "")
871                                                 {
872                                                         param = param + " " + append;
873                                                 }
874                                         }
875                                 }
876                                 item++;
877                                 n.push_back(param);
878                         }
879                 }
880                 return n;
881         }
882
883         bool ProcessLine(std::string line)
884         {
885                 char* l = (char*)line.c_str();
886                 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
887                         l[strlen(l)-1] = '\0';
888                 line = l;
889                 if (line == "")
890                         return true;
891                 Srv->Log(DEBUG,"inbound-line: '"+line+"'");
892                 std::deque<std::string> params = this->Split(line,true);
893                 std::string command = "";
894                 std::string prefix = "";
895                 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
896                 {
897                         prefix = params[0];
898                         command = params[1];
899                         char* pref = (char*)prefix.c_str();
900                         prefix = ++pref;
901                         params.pop_front();
902                         params.pop_front();
903                 }
904                 else
905                 {
906                         prefix = "";
907                         command = params[0];
908                         params.pop_front();
909                 }
910                 
911                 switch (this->LinkState)
912                 {
913                         TreeServer* Node;
914                         
915                         case WAIT_AUTH_1:
916                                 // Waiting for SERVER command from remote server. Server initiating
917                                 // the connection sends the first SERVER command, listening server
918                                 // replies with theirs if its happy, then if the initiator is happy,
919                                 // it starts to send its net sync, which starts the merge, otherwise
920                                 // it sends an ERROR.
921                                 if (command == "SERVER")
922                                 {
923                                         return this->Inbound_Server(params);
924                                 }
925                                 else if (command == "ERROR")
926                                 {
927                                         return this->Error(params);
928                                 }
929                         break;
930                         case WAIT_AUTH_2:
931                                 // Waiting for start of other side's netmerge to say they liked our
932                                 // password.
933                                 if (command == "SERVER")
934                                 {
935                                         // cant do this, they sent it to us in the WAIT_AUTH_1 state!
936                                         // silently ignore.
937                                         return true;
938                                 }
939                                 else if (command == "BURST")
940                                 {
941                                         this->LinkState = CONNECTED;
942                                         Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
943                                         TreeRoot->AddChild(Node);
944                                         params.clear();
945                                         params.push_back(InboundServerName);
946                                         params.push_back("*");
947                                         params.push_back("1");
948                                         params.push_back(":"+InboundDescription);
949                                         DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
950                                         this->DoBurst(Node);
951                                 }
952                                 else if (command == "ERROR")
953                                 {
954                                         return this->Error(params);
955                                 }
956                                 
957                         break;
958                         case LISTENER:
959                                 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
960                                 return false;
961                         break;
962                         case CONNECTING:
963                                 if (command == "SERVER")
964                                 {
965                                         // another server we connected to, which was in WAIT_AUTH_1 state,
966                                         // has just sent us their credentials. If we get this far, theyre
967                                         // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
968                                         // if we're happy with this, we should send our netburst which
969                                         // kickstarts the merge.
970                                         return this->Outbound_Reply_Server(params);
971                                 }
972                                 else if (command == "ERROR")
973                                 {
974                                         return this->Error(params);
975                                 }
976                         break;
977                         case CONNECTED:
978                                 // This is the 'authenticated' state, when all passwords
979                                 // have been exchanged and anything past this point is taken
980                                 // as gospel.
981                                 std::string target = "";
982                                 if ((command == "NICK") && (params.size() > 1))
983                                 {
984                                         return this->IntroduceClient(prefix,params);
985                                 }
986                                 else if (command == "FJOIN")
987                                 {
988                                         return this->ForceJoin(prefix,params);
989                                 }
990                                 else if (command == "SERVER")
991                                 {
992                                         return this->RemoteServer(prefix,params);
993                                 }
994                                 else if (command == "ERROR")
995                                 {
996                                         return this->Error(params);
997                                 }
998                                 else if (command == "OPERTYPE")
999                                 {
1000                                         return this->OperType(prefix,params);
1001                                 }
1002                                 else if (command == "FMODE")
1003                                 {
1004                                         return this->ForceMode(prefix,params);
1005                                 }
1006                                 else if (command == "KILL")
1007                                 {
1008                                         return this->RemoteKill(prefix,params);
1009                                 }
1010                                 else if (command == "FTOPIC")
1011                                 {
1012                                         return this->ForceTopic(prefix,params);
1013                                 }
1014                                 else if (command == "REHASH")
1015                                 {
1016                                         return this->RemoteRehash(prefix,params);
1017                                 }
1018                                 else if (command == "SQUIT")
1019                                 {
1020                                         if (params.size() == 2)
1021                                         {
1022                                                 this->Squit(FindServer(params[0]),params[1]);
1023                                         }
1024                                         return true;
1025                                 }
1026                                 else
1027                                 {
1028                                         // not a special inter-server command.
1029                                         // Emulate the actual user doing the command,
1030                                         // this saves us having a huge ugly parser.
1031                                         userrec* who = Srv->FindNick(prefix);
1032                                         std::string sourceserv = this->myhost;
1033                                         if (this->InboundServerName != "")
1034                                         {
1035                                                 sourceserv = this->InboundServerName;
1036                                         }
1037                                         if (who)
1038                                         {
1039                                                 // its a user
1040                                                 target = who->server;
1041                                                 char* strparams[127];
1042                                                 for (unsigned int q = 0; q < params.size(); q++)
1043                                                 {
1044                                                         strparams[q] = (char*)params[q].c_str();
1045                                                 }
1046                                                 log(DEBUG,"*** CALL COMMAND HANDLER FOR %s, SOURCE: '%s'",command.c_str(),who->nick);
1047                                                 Srv->CallCommandHandler(command, strparams, params.size(), who);
1048                                         }
1049                                         else
1050                                         {
1051                                                 // its not a user. Its either a server, or somethings screwed up.
1052                                                 if (IsServer(prefix))
1053                                                 {
1054                                                         target = Srv->GetServerName();
1055                                                 }
1056                                                 else
1057                                                 {
1058                                                         log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
1059                                                         return true;
1060                                                 }
1061                                         }
1062                                         return DoOneToAllButSenderRaw(line,sourceserv);
1063
1064                                 }
1065                                 return true;
1066                         break;  
1067                 }
1068                 return true;
1069         }
1070
1071         virtual std::string GetName()
1072         {
1073                 std::string sourceserv = this->myhost;
1074                 if (this->InboundServerName != "")
1075                 {
1076                         sourceserv = this->InboundServerName;
1077                 }
1078                 return sourceserv;
1079         }
1080
1081         virtual void OnTimeout()
1082         {
1083                 if (this->LinkState == CONNECTING)
1084                 {
1085                         Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
1086                 }
1087         }
1088
1089         virtual void OnClose()
1090         {
1091                 // Connection closed.
1092                 // If the connection is fully up (state CONNECTED)
1093                 // then propogate a netsplit to all peers.
1094                 std::string quitserver = this->myhost;
1095                 if (this->InboundServerName != "")
1096                 {
1097                         quitserver = this->InboundServerName;
1098                 }
1099                 TreeServer* s = FindServer(quitserver);
1100                 if (s)
1101                 {
1102                         Squit(s,"Remote host closed the connection");
1103                 }
1104         }
1105
1106         virtual int OnIncomingConnection(int newsock, char* ip)
1107         {
1108                 TreeSocket* s = new TreeSocket(newsock, ip);
1109                 Srv->AddSocket(s);
1110                 return true;
1111         }
1112 };
1113
1114 bool DoOneToAllButSenderRaw(std::string data,std::string omit)
1115 {
1116         TreeServer* omitroute = BestRouteTo(omit);
1117         for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1118         {
1119                 TreeServer* Route = TreeRoot->GetChild(x);
1120                 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1121                 {
1122                         TreeSocket* Sock = Route->GetSocket();
1123                         log(DEBUG,"Sending RAW to %s",Route->GetName().c_str());
1124                         Sock->WriteLine(data);
1125                 }
1126         }
1127         return true;
1128 }
1129
1130 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit)
1131 {
1132         log(DEBUG,"ALLBUTONE: Comes from %s SHOULD NOT go back to %s",prefix.c_str(),omit.c_str());
1133         TreeServer* omitroute = BestRouteTo(omit);
1134         // TODO: Special stuff with privmsg and notice
1135         std::string FullLine = ":" + prefix + " " + command;
1136         for (unsigned int x = 0; x < params.size(); x++)
1137         {
1138                 FullLine = FullLine + " " + params[x];
1139         }
1140         for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1141         {
1142                 TreeServer* Route = TreeRoot->GetChild(x);
1143                 // Send the line IF:
1144                 // The route has a socket (its a direct connection)
1145                 // The route isnt the one to be omitted
1146                 // The route isnt the path to the one to be omitted
1147                 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1148                 {
1149                         TreeSocket* Sock = Route->GetSocket();
1150                         log(DEBUG,"Sending to %s",Route->GetName().c_str());
1151                         Sock->WriteLine(FullLine);
1152                 }
1153         }
1154         return true;
1155 }
1156
1157 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params)
1158 {
1159         Srv->Log(DEBUG,"ONETOMANY: "+command);
1160         std::string FullLine = ":" + prefix + " " + command;
1161         for (unsigned int x = 0; x < params.size(); x++)
1162         {
1163                 FullLine = FullLine + " " + params[x];
1164         }
1165         for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1166         {
1167                 TreeServer* Route = TreeRoot->GetChild(x);
1168                 if (Route->GetSocket())
1169                 {
1170                         TreeSocket* Sock = Route->GetSocket();
1171                         Sock->WriteLine(FullLine);
1172                 }
1173         }
1174         return true;
1175 }
1176
1177 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target)
1178 {
1179         TreeServer* Route = BestRouteTo(target);
1180         if (Route)
1181         {
1182                 std::string FullLine = ":" + prefix + " " + command;
1183                 for (unsigned int x = 0; x < params.size(); x++)
1184                 {
1185                         FullLine = FullLine + " " + params[x];
1186                 }
1187                 if (Route->GetSocket())
1188                 {
1189                         TreeSocket* Sock = Route->GetSocket();
1190                         Sock->WriteLine(FullLine);
1191                 }
1192                 return true;
1193         }
1194         else
1195         {
1196                 log(DEBUG,"Could not route message with target %s: %s",target.c_str(),command.c_str());
1197                 return true;
1198         }
1199 }
1200
1201
1202 class ModuleSpanningTree : public Module
1203 {
1204         std::vector<TreeSocket*> Bindings;
1205         int line;
1206
1207  public:
1208
1209         void ReadConfiguration(bool rebind)
1210         {
1211                 if (rebind)
1212                 {
1213                         for (int j =0; j < Conf->Enumerate("bind"); j++)
1214                         {
1215                                 std::string Type = Conf->ReadValue("bind","type",j);
1216                                 std::string IP = Conf->ReadValue("bind","address",j);
1217                                 long Port = Conf->ReadInteger("bind","port",j,true);
1218                                 if (Type == "servers")
1219                                 {
1220                                         if (IP == "*")
1221                                         {
1222                                                 IP = "";
1223                                         }
1224                                         TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
1225                                         if (listener->GetState() == I_LISTENING)
1226                                         {
1227                                                 Srv->AddSocket(listener);
1228                                                 Bindings.push_back(listener);
1229                                         }
1230                                         else
1231                                         {
1232                                                 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
1233                                                 listener->Close();
1234                                                 delete listener;
1235                                         }
1236                                 }
1237                         }
1238                 }
1239                 LinkBlocks.clear();
1240                 for (int j =0; j < Conf->Enumerate("link"); j++)
1241                 {
1242                         Link L;
1243                         L.Name = Conf->ReadValue("link","name",j);
1244                         L.IPAddr = Conf->ReadValue("link","ipaddr",j);
1245                         L.Port = Conf->ReadInteger("link","port",j,true);
1246                         L.SendPass = Conf->ReadValue("link","sendpass",j);
1247                         L.RecvPass = Conf->ReadValue("link","recvpass",j);
1248                         LinkBlocks.push_back(L);
1249                         log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
1250                 }
1251         }
1252
1253         ModuleSpanningTree()
1254         {
1255                 Srv = new Server;
1256                 Conf = new ConfigReader;
1257                 Bindings.clear();
1258
1259                 // Create the root of the tree
1260                 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
1261
1262                 ReadConfiguration(true);
1263         }
1264
1265         void ShowLinks(TreeServer* Current, userrec* user, int hops)
1266         {
1267                 std::string Parent = TreeRoot->GetName();
1268                 if (Current->GetParent())
1269                 {
1270                         Parent = Current->GetParent()->GetName();
1271                 }
1272                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1273                 {
1274                         ShowLinks(Current->GetChild(q),user,hops+1);
1275                 }
1276                 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
1277         }
1278
1279         void HandleLinks(char** parameters, int pcnt, userrec* user)
1280         {
1281                 ShowLinks(TreeRoot,user,0);
1282                 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
1283                 return;
1284         }
1285
1286         void HandleLusers(char** parameters, int pcnt, userrec* user)
1287         {
1288                 return;
1289         }
1290
1291         // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
1292
1293         void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
1294         {
1295                 if (line < 128)
1296                 {
1297                         for (int t = 0; t < depth; t++)
1298                         {
1299                                 matrix[line][t] = ' ';
1300                         }
1301                         strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
1302                         line++;
1303                         for (unsigned int q = 0; q < Current->ChildCount(); q++)
1304                         {
1305                                 ShowMap(Current->GetChild(q),user,depth+2,matrix);
1306                         }
1307                 }
1308         }
1309
1310         // Ok, prepare to be confused.
1311         // After much mulling over how to approach this, it struck me that
1312         // the 'usual' way of doing a /MAP isnt the best way. Instead of
1313         // keeping track of a ton of ascii characters, and line by line
1314         // under recursion working out where to place them using multiplications
1315         // and divisons, we instead render the map onto a backplane of characters
1316         // (a character matrix), then draw the branches as a series of "L" shapes
1317         // from the nodes. This is not only friendlier on CPU it uses less stack.
1318
1319         void HandleMap(char** parameters, int pcnt, userrec* user)
1320         {
1321                 // This array represents a virtual screen which we will
1322                 // "scratch" draw to, as the console device of an irc
1323                 // client does not provide for a proper terminal.
1324                 char matrix[128][80];
1325                 for (unsigned int t = 0; t < 128; t++)
1326                 {
1327                         matrix[t][0] = '\0';
1328                 }
1329                 line = 0;
1330                 // The only recursive bit is called here.
1331                 ShowMap(TreeRoot,user,0,matrix);
1332                 // Process each line one by one. The algorithm has a limit of
1333                 // 128 servers (which is far more than a spanning tree should have
1334                 // anyway, so we're ok). This limit can be raised simply by making
1335                 // the character matrix deeper, 128 rows taking 10k of memory.
1336                 for (int l = 1; l < line; l++)
1337                 {
1338                         // scan across the line looking for the start of the
1339                         // servername (the recursive part of the algorithm has placed
1340                         // the servers at indented positions depending on what they
1341                         // are related to)
1342                         int first_nonspace = 0;
1343                         while (matrix[l][first_nonspace] == ' ')
1344                         {
1345                                 first_nonspace++;
1346                         }
1347                         first_nonspace--;
1348                         // Draw the `- (corner) section: this may be overwritten by
1349                         // another L shape passing along the same vertical pane, becoming
1350                         // a |- (branch) section instead.
1351                         matrix[l][first_nonspace] = '-';
1352                         matrix[l][first_nonspace-1] = '`';
1353                         int l2 = l - 1;
1354                         // Draw upwards until we hit the parent server, causing possibly
1355                         // other corners (`-) to become branches (|-)
1356                         while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
1357                         {
1358                                 matrix[l2][first_nonspace-1] = '|';
1359                                 l2--;
1360                         }
1361                 }
1362                 // dump the whole lot to the user. This is the easy bit, honest.
1363                 for (int t = 0; t < line; t++)
1364                 {
1365                         WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
1366                 }
1367                 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
1368                 return;
1369         }
1370
1371         int HandleSquit(char** parameters, int pcnt, userrec* user)
1372         {
1373                 return 1;
1374         }
1375
1376         int HandleConnect(char** parameters, int pcnt, userrec* user)
1377         {
1378                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1379                 {
1380                         if (Srv->MatchText(x->Name.c_str(),parameters[0]))
1381                         {
1382                                 WriteServ(user->fd,"NOTICE %s :*** CONNECT: Connecting to server: %s (%s:%d)",user->nick,x->Name.c_str(),x->IPAddr.c_str(),x->Port);
1383                                 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1384                                 Srv->AddSocket(newsocket);
1385                                 return 1;
1386                         }
1387                 }
1388                 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No matching server could be found in the config file.",user->nick);
1389                 return 1;
1390         }
1391
1392         virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
1393         {
1394                 if (command == "CONNECT")
1395                 {
1396                         return this->HandleConnect(parameters,pcnt,user);
1397                 }
1398                 else if (command == "SQUIT")
1399                 {
1400                         return this->HandleSquit(parameters,pcnt,user);
1401                 }
1402                 else if (command == "MAP")
1403                 {
1404                         this->HandleMap(parameters,pcnt,user);
1405                         return 1;
1406                 }
1407                 else if (command == "LUSERS")
1408                 {
1409                         this->HandleLusers(parameters,pcnt,user);
1410                         return 1;
1411                 }
1412                 else if (command == "LINKS")
1413                 {
1414                         this->HandleLinks(parameters,pcnt,user);
1415                         return 1;
1416                 }
1417                 return 0;
1418         }
1419
1420         virtual void OnGetServerDescription(std::string servername,std::string &description)
1421         {
1422                 TreeServer* s = FindServer(servername);
1423                 if (s)
1424                 {
1425                         description = s->GetDesc();
1426                 }
1427         }
1428
1429         virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
1430         {
1431                 if (std::string(source->server) == Srv->GetServerName())
1432                 {
1433                         std::deque<std::string> params;
1434                         params.push_back(dest->nick);
1435                         params.push_back(channel->name);
1436                         DoOneToMany(source->nick,"INVITE",params);
1437                 }
1438         }
1439
1440         virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
1441         {
1442                 std::deque<std::string> params;
1443                 params.push_back(chan->name);
1444                 params.push_back(":"+topic);
1445                 DoOneToMany(user->nick,"TOPIC",params);
1446         }
1447
1448         virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
1449         {
1450                 if (target_type == TYPE_USER)
1451                 {
1452                         userrec* d = (userrec*)dest;
1453                         if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1454                         {
1455                                 std::deque<std::string> params;
1456                                 params.clear();
1457                                 params.push_back(d->nick);
1458                                 params.push_back(":"+text);
1459                                 DoOneToOne(user->nick,"NOTICE",params,d->server);
1460                         }
1461                 }
1462                 else
1463                 {
1464                         if (std::string(user->server) == Srv->GetServerName())
1465                         {
1466                                 chanrec *c = (chanrec*)dest;
1467                                 std::deque<std::string> params;
1468                                 params.push_back(c->name);
1469                                 params.push_back(":"+text);
1470                                 DoOneToMany(user->nick,"NOTICE",params);
1471                         }
1472                 }
1473         }
1474
1475         virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
1476         {
1477                 if (target_type == TYPE_USER)
1478                 {
1479                         // route private messages which are targetted at clients only to the server
1480                         // which needs to receive them
1481                         userrec* d = (userrec*)dest;
1482                         if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1483                         {
1484                                 std::deque<std::string> params;
1485                                 params.clear();
1486                                 params.push_back(d->nick);
1487                                 params.push_back(":"+text);
1488                                 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
1489                         }
1490                 }
1491                 else
1492                 {
1493                         if (std::string(user->server) == Srv->GetServerName())
1494                         {
1495                                 chanrec *c = (chanrec*)dest;
1496                                 std::deque<std::string> params;
1497                                 params.push_back(c->name);
1498                                 params.push_back(":"+text);
1499                                 DoOneToMany(user->nick,"PRIVMSG",params);
1500                         }
1501                 }
1502         }
1503
1504         virtual void OnUserJoin(userrec* user, chanrec* channel)
1505         {
1506                 // Only do this for local users
1507                 if (std::string(user->server) == Srv->GetServerName())
1508                 {
1509                         log(DEBUG,"**** User on %s JOINS %s",user->server,channel->name);
1510                         std::deque<std::string> params;
1511                         params.clear();
1512                         params.push_back(channel->name);
1513                         if (*channel->key)
1514                         {
1515                                 log(DEBUG,"**** With key %s",channel->key);
1516                                 // if the channel has a key, force the join by emulating the key.
1517                                 params.push_back(channel->key);
1518                         }
1519                         DoOneToMany(user->nick,"JOIN",params);
1520                 }
1521         }
1522
1523         virtual void OnUserPart(userrec* user, chanrec* channel)
1524         {
1525                 if (std::string(user->server) == Srv->GetServerName())
1526                 {
1527                         log(DEBUG,"**** User on %s PARTS %s",user->server,channel->name);
1528                         std::deque<std::string> params;
1529                         params.clear();
1530                         params.push_back(channel->name);
1531                         DoOneToMany(user->nick,"PART",params);
1532                 }
1533         }
1534
1535         virtual void OnUserConnect(userrec* user)
1536         {
1537                 char agestr[MAXBUF];
1538                 if (std::string(user->server) == Srv->GetServerName())
1539                 {
1540                         log(DEBUG,"**** User on %s CONNECTS: %s",user->server,user->nick);
1541                         std::deque<std::string> params;
1542                         snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
1543                         params.clear();
1544                         params.push_back(agestr);
1545                         params.push_back(user->nick);
1546                         params.push_back(user->host);
1547                         params.push_back(user->dhost);
1548                         params.push_back(user->ident);
1549                         params.push_back("+"+std::string(user->modes));
1550                         params.push_back(user->ip);
1551                         params.push_back(":"+std::string(user->fullname));
1552                         DoOneToMany(Srv->GetServerName(),"NICK",params);
1553                 }
1554         }
1555
1556         virtual void OnUserQuit(userrec* user, std::string reason)
1557         {
1558                 if (std::string(user->server) == Srv->GetServerName())
1559                 {
1560                         log(DEBUG,"**** User on %s QUITS: %s",user->server,user->nick);
1561                         std::deque<std::string> params;
1562                         params.push_back(":"+reason);
1563                         DoOneToMany(user->nick,"QUIT",params);
1564                 }
1565         }
1566
1567         virtual void OnUserPostNick(userrec* user, std::string oldnick)
1568         {
1569                 if (std::string(user->server) == Srv->GetServerName())
1570                 {
1571                         log(DEBUG,"**** User on %s changes NICK: %s",user->server,user->nick);
1572                         std::deque<std::string> params;
1573                         params.push_back(user->nick);
1574                         DoOneToMany(oldnick,"NICK",params);
1575                 }
1576         }
1577
1578         virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
1579         {
1580                 if (std::string(source->server) == Srv->GetServerName())
1581                 {
1582                         log(DEBUG,"**** User on %s KICKs: %s %s",source->server,source->nick,user->nick);
1583                         std::deque<std::string> params;
1584                         params.push_back(chan->name);
1585                         params.push_back(user->nick);
1586                         params.push_back(":"+reason);
1587                         DoOneToMany(source->nick,"KICK",params);
1588                 }
1589         }
1590
1591         virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
1592         {
1593                 std::deque<std::string> params;
1594                 params.push_back(dest->nick);
1595                 params.push_back(":"+reason);
1596                 DoOneToMany(source->nick,"KILL",params);
1597         }
1598
1599         virtual void OnRehash(std::string parameter)
1600         {
1601                 if (parameter != "")
1602                 {
1603                         std::deque<std::string> params;
1604                         params.push_back(parameter);
1605                         DoOneToMany(Srv->GetServerName(),"REHASH",params);
1606                         // check for self
1607                         if (Srv->MatchText(Srv->GetServerName(),parameter))
1608                         {
1609                                 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
1610                                 Srv->RehashServer();
1611                         }
1612                 }
1613         }
1614
1615         // note: the protocol does not allow direct umode +o except
1616         // via NICK with 8 params. sending OPERTYPE infers +o modechange
1617         // locally.
1618         virtual void OnOper(userrec* user, std::string opertype)
1619         {
1620                 if (std::string(user->server) == Srv->GetServerName())
1621                 {
1622                         std::deque<std::string> params;
1623                         params.push_back(opertype);
1624                         DoOneToMany(user->nick,"OPERTYPE",params);
1625                 }
1626         }
1627
1628         virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
1629         {
1630                 log(DEBUG,"*** ONMODE TRIGGER");
1631                 if (std::string(user->server) == Srv->GetServerName())
1632                 {
1633                         log(DEBUG,"*** LOCAL");
1634                         if (target_type == TYPE_USER)
1635                         {
1636                                 userrec* u = (userrec*)dest;
1637                                 std::deque<std::string> params;
1638                                 params.push_back(u->nick);
1639                                 params.push_back(text);
1640                                 DoOneToMany(user->nick,"MODE",params);
1641                         }
1642                         else
1643                         {
1644                                 chanrec* c = (chanrec*)dest;
1645                                 std::deque<std::string> params;
1646                                 params.push_back(c->name);
1647                                 params.push_back(text);
1648                                 DoOneToMany(user->nick,"MODE",params);
1649                         }
1650                 }
1651         }
1652
1653         virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
1654         {
1655                 TreeSocket* s = (TreeSocket*)opaque;
1656                 if (target)
1657                 {
1658                         if (target_type == TYPE_USER)
1659                         {
1660                                 userrec* u = (userrec*)target;
1661                                 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
1662                         }
1663                         else
1664                         {
1665                                 chanrec* c = (chanrec*)target;
1666                                 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
1667                         }
1668                 }
1669         }
1670
1671         virtual ~ModuleSpanningTree()
1672         {
1673                 delete Srv;
1674         }
1675
1676         virtual Version GetVersion()
1677         {
1678                 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
1679         }
1680 };
1681
1682
1683 class ModuleSpanningTreeFactory : public ModuleFactory
1684 {
1685  public:
1686         ModuleSpanningTreeFactory()
1687         {
1688         }
1689         
1690         ~ModuleSpanningTreeFactory()
1691         {
1692         }
1693         
1694         virtual Module * CreateModule()
1695         {
1696                 TreeProtocolModule = new ModuleSpanningTree;
1697                 return TreeProtocolModule;
1698         }
1699         
1700 };
1701
1702
1703 extern "C" void * init_module( void )
1704 {
1705         return new ModuleSpanningTreeFactory;
1706 }
1707