]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree.cpp
Fixed loss of padding spaces in privmsgs, etc
[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                         TreeProtocolModule->ReadConfiguration(false);
731                 }
732                 DoOneToAllButSender(prefix,"REHASH",params,prefix);
733                 return true;
734         }
735
736         bool RemoteKill(std::string prefix, std::deque<std::string> params)
737         {
738                 if (params.size() != 2)
739                         return true;
740                 std::string nick = params[0];
741                 std::string reason = params[1];
742                 userrec* u = Srv->FindNick(prefix);
743                 userrec* who = Srv->FindNick(nick);
744                 if (who)
745                 {
746                         std::string sourceserv = prefix;
747                         if (u)
748                         {
749                                 sourceserv = u->server;
750                         }
751                         params[1] = ":" + params[1];
752                         DoOneToAllButSender(prefix,"KILL",params,sourceserv);
753                         Srv->QuitUser(who,reason);
754                 }
755                 return true;
756         }
757
758         bool RemoteServer(std::string prefix, std::deque<std::string> params)
759         {
760                 if (params.size() < 4)
761                         return false;
762                 std::string servername = params[0];
763                 std::string password = params[1];
764                 // hopcount is not used for a remote server, we calculate this ourselves
765                 std::string description = params[3];
766                 TreeServer* ParentOfThis = FindServer(prefix);
767                 if (!ParentOfThis)
768                 {
769                         this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
770                         return false;
771                 }
772                 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
773                 ParentOfThis->AddChild(Node);
774                 params[3] = ":" + params[3];
775                 DoOneToAllButSender(prefix,"SERVER",params,prefix);
776                 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
777                 return true;
778         }
779
780         bool Outbound_Reply_Server(std::deque<std::string> params)
781         {
782                 if (params.size() < 4)
783                         return false;
784                 std::string servername = params[0];
785                 std::string password = params[1];
786                 int hops = atoi(params[2].c_str());
787                 if (hops)
788                 {
789                         this->WriteLine("ERROR :Server too far away for authentication");
790                         return false;
791                 }
792                 std::string description = params[3];
793                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
794                 {
795                         if ((x->Name == servername) && (x->RecvPass == password))
796                         {
797                                 // Begin the sync here. this kickstarts the
798                                 // other side, waiting in WAIT_AUTH_2 state,
799                                 // into starting their burst, as it shows
800                                 // that we're happy.
801                                 this->LinkState = CONNECTED;
802                                 // we should add the details of this server now
803                                 // to the servers tree, as a child of the root
804                                 // node.
805                                 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
806                                 TreeRoot->AddChild(Node);
807                                 params[3] = ":" + params[3];
808                                 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
809                                 this->DoBurst(Node);
810                                 return true;
811                         }
812                 }
813                 this->WriteLine("ERROR :Invalid credentials");
814                 return false;
815         }
816
817         bool Inbound_Server(std::deque<std::string> params)
818         {
819                 if (params.size() < 4)
820                         return false;
821                 std::string servername = params[0];
822                 std::string password = params[1];
823                 int hops = atoi(params[2].c_str());
824                 if (hops)
825                 {
826                         this->WriteLine("ERROR :Server too far away for authentication");
827                         return false;
828                 }
829                 std::string description = params[3];
830                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
831                 {
832                         if ((x->Name == servername) && (x->RecvPass == password))
833                         {
834                                 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
835                                 this->InboundServerName = servername;
836                                 this->InboundDescription = description;
837                                 // this is good. Send our details: Our server name and description and hopcount of 0,
838                                 // along with the sendpass from this block.
839                                 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
840                                 // move to the next state, we are now waiting for THEM.
841                                 this->LinkState = WAIT_AUTH_2;
842                                 return true;
843                         }
844                 }
845                 this->WriteLine("ERROR :Invalid credentials");
846                 return false;
847         }
848
849         std::deque<std::string> Split(std::string line, bool stripcolon)
850         {
851                 std::deque<std::string> n;
852                 std::stringstream s(line);
853                 std::string param = "";
854                 n.clear();
855                 int item = 0;
856                 while (!s.eof())
857                 {
858                         s >> param;
859                         //if ((param != "") && (param != "\n"))
860                         //{
861                                 if ((param.c_str()[0] == ':') && (item))
862                                 {
863                                         char* str = (char*)param.c_str();
864                                         str++;
865                                         param = str;
866                                         std::string append;
867                                         while (!s.eof())
868                                         {
869                                                 append = "";
870                                                 s >> append;
871                                                 if (append != "")
872                                                 {
873                                                         param = param + " " + append;
874                                                 }
875                                         }
876                                 }
877                                 item++;
878                                 n.push_back(param);
879                         //}
880                 }
881                 return n;
882         }
883
884         bool ProcessLine(std::string line)
885         {
886                 char* l = (char*)line.c_str();
887                 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
888                         l[strlen(l)-1] = '\0';
889                 line = l;
890                 if (line == "")
891                         return true;
892                 Srv->Log(DEBUG,"inbound-line: '"+line+"'");
893                 std::deque<std::string> params = this->Split(line,true);
894                 std::string command = "";
895                 std::string prefix = "";
896                 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
897                 {
898                         prefix = params[0];
899                         command = params[1];
900                         char* pref = (char*)prefix.c_str();
901                         prefix = ++pref;
902                         params.pop_front();
903                         params.pop_front();
904                 }
905                 else
906                 {
907                         prefix = "";
908                         command = params[0];
909                         params.pop_front();
910                 }
911                 
912                 switch (this->LinkState)
913                 {
914                         TreeServer* Node;
915                         
916                         case WAIT_AUTH_1:
917                                 // Waiting for SERVER command from remote server. Server initiating
918                                 // the connection sends the first SERVER command, listening server
919                                 // replies with theirs if its happy, then if the initiator is happy,
920                                 // it starts to send its net sync, which starts the merge, otherwise
921                                 // it sends an ERROR.
922                                 if (command == "SERVER")
923                                 {
924                                         return this->Inbound_Server(params);
925                                 }
926                                 else if (command == "ERROR")
927                                 {
928                                         return this->Error(params);
929                                 }
930                         break;
931                         case WAIT_AUTH_2:
932                                 // Waiting for start of other side's netmerge to say they liked our
933                                 // password.
934                                 if (command == "SERVER")
935                                 {
936                                         // cant do this, they sent it to us in the WAIT_AUTH_1 state!
937                                         // silently ignore.
938                                         return true;
939                                 }
940                                 else if (command == "BURST")
941                                 {
942                                         this->LinkState = CONNECTED;
943                                         Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
944                                         TreeRoot->AddChild(Node);
945                                         params.clear();
946                                         params.push_back(InboundServerName);
947                                         params.push_back("*");
948                                         params.push_back("1");
949                                         params.push_back(":"+InboundDescription);
950                                         DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
951                                         this->DoBurst(Node);
952                                 }
953                                 else if (command == "ERROR")
954                                 {
955                                         return this->Error(params);
956                                 }
957                                 
958                         break;
959                         case LISTENER:
960                                 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
961                                 return false;
962                         break;
963                         case CONNECTING:
964                                 if (command == "SERVER")
965                                 {
966                                         // another server we connected to, which was in WAIT_AUTH_1 state,
967                                         // has just sent us their credentials. If we get this far, theyre
968                                         // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
969                                         // if we're happy with this, we should send our netburst which
970                                         // kickstarts the merge.
971                                         return this->Outbound_Reply_Server(params);
972                                 }
973                                 else if (command == "ERROR")
974                                 {
975                                         return this->Error(params);
976                                 }
977                         break;
978                         case CONNECTED:
979                                 // This is the 'authenticated' state, when all passwords
980                                 // have been exchanged and anything past this point is taken
981                                 // as gospel.
982                                 std::string target = "";
983                                 if ((command == "NICK") && (params.size() > 1))
984                                 {
985                                         return this->IntroduceClient(prefix,params);
986                                 }
987                                 else if (command == "FJOIN")
988                                 {
989                                         return this->ForceJoin(prefix,params);
990                                 }
991                                 else if (command == "SERVER")
992                                 {
993                                         return this->RemoteServer(prefix,params);
994                                 }
995                                 else if (command == "ERROR")
996                                 {
997                                         return this->Error(params);
998                                 }
999                                 else if (command == "OPERTYPE")
1000                                 {
1001                                         return this->OperType(prefix,params);
1002                                 }
1003                                 else if (command == "FMODE")
1004                                 {
1005                                         return this->ForceMode(prefix,params);
1006                                 }
1007                                 else if (command == "KILL")
1008                                 {
1009                                         return this->RemoteKill(prefix,params);
1010                                 }
1011                                 else if (command == "FTOPIC")
1012                                 {
1013                                         return this->ForceTopic(prefix,params);
1014                                 }
1015                                 else if (command == "REHASH")
1016                                 {
1017                                         return this->RemoteRehash(prefix,params);
1018                                 }
1019                                 else if (command == "SQUIT")
1020                                 {
1021                                         if (params.size() == 2)
1022                                         {
1023                                                 this->Squit(FindServer(params[0]),params[1]);
1024                                         }
1025                                         return true;
1026                                 }
1027                                 else
1028                                 {
1029                                         // not a special inter-server command.
1030                                         // Emulate the actual user doing the command,
1031                                         // this saves us having a huge ugly parser.
1032                                         userrec* who = Srv->FindNick(prefix);
1033                                         std::string sourceserv = this->myhost;
1034                                         if (this->InboundServerName != "")
1035                                         {
1036                                                 sourceserv = this->InboundServerName;
1037                                         }
1038                                         if (who)
1039                                         {
1040                                                 // its a user
1041                                                 target = who->server;
1042                                                 char* strparams[127];
1043                                                 for (unsigned int q = 0; q < params.size(); q++)
1044                                                 {
1045                                                         strparams[q] = (char*)params[q].c_str();
1046                                                 }
1047                                                 log(DEBUG,"*** CALL COMMAND HANDLER FOR %s, SOURCE: '%s'",command.c_str(),who->nick);
1048                                                 Srv->CallCommandHandler(command, strparams, params.size(), who);
1049                                         }
1050                                         else
1051                                         {
1052                                                 // its not a user. Its either a server, or somethings screwed up.
1053                                                 if (IsServer(prefix))
1054                                                 {
1055                                                         target = Srv->GetServerName();
1056                                                 }
1057                                                 else
1058                                                 {
1059                                                         log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
1060                                                         return true;
1061                                                 }
1062                                         }
1063                                         return DoOneToAllButSenderRaw(line,sourceserv);
1064
1065                                 }
1066                                 return true;
1067                         break;  
1068                 }
1069                 return true;
1070         }
1071
1072         virtual std::string GetName()
1073         {
1074                 std::string sourceserv = this->myhost;
1075                 if (this->InboundServerName != "")
1076                 {
1077                         sourceserv = this->InboundServerName;
1078                 }
1079                 return sourceserv;
1080         }
1081
1082         virtual void OnTimeout()
1083         {
1084                 if (this->LinkState == CONNECTING)
1085                 {
1086                         Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
1087                 }
1088         }
1089
1090         virtual void OnClose()
1091         {
1092                 // Connection closed.
1093                 // If the connection is fully up (state CONNECTED)
1094                 // then propogate a netsplit to all peers.
1095                 std::string quitserver = this->myhost;
1096                 if (this->InboundServerName != "")
1097                 {
1098                         quitserver = this->InboundServerName;
1099                 }
1100                 TreeServer* s = FindServer(quitserver);
1101                 if (s)
1102                 {
1103                         Squit(s,"Remote host closed the connection");
1104                 }
1105         }
1106
1107         virtual int OnIncomingConnection(int newsock, char* ip)
1108         {
1109                 TreeSocket* s = new TreeSocket(newsock, ip);
1110                 Srv->AddSocket(s);
1111                 return true;
1112         }
1113 };
1114
1115 bool DoOneToAllButSenderRaw(std::string data,std::string omit)
1116 {
1117         TreeServer* omitroute = BestRouteTo(omit);
1118         for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1119         {
1120                 TreeServer* Route = TreeRoot->GetChild(x);
1121                 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1122                 {
1123                         TreeSocket* Sock = Route->GetSocket();
1124                         log(DEBUG,"Sending RAW to %s",Route->GetName().c_str());
1125                         Sock->WriteLine(data);
1126                 }
1127         }
1128         return true;
1129 }
1130
1131 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit)
1132 {
1133         log(DEBUG,"ALLBUTONE: Comes from %s SHOULD NOT go back to %s",prefix.c_str(),omit.c_str());
1134         TreeServer* omitroute = BestRouteTo(omit);
1135         // TODO: Special stuff with privmsg and notice
1136         std::string FullLine = ":" + prefix + " " + command;
1137         for (unsigned int x = 0; x < params.size(); x++)
1138         {
1139                 FullLine = FullLine + " " + params[x];
1140         }
1141         for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1142         {
1143                 TreeServer* Route = TreeRoot->GetChild(x);
1144                 // Send the line IF:
1145                 // The route has a socket (its a direct connection)
1146                 // The route isnt the one to be omitted
1147                 // The route isnt the path to the one to be omitted
1148                 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1149                 {
1150                         TreeSocket* Sock = Route->GetSocket();
1151                         log(DEBUG,"Sending to %s",Route->GetName().c_str());
1152                         Sock->WriteLine(FullLine);
1153                 }
1154         }
1155         return true;
1156 }
1157
1158 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params)
1159 {
1160         Srv->Log(DEBUG,"ONETOMANY: "+command);
1161         std::string FullLine = ":" + prefix + " " + command;
1162         for (unsigned int x = 0; x < params.size(); x++)
1163         {
1164                 FullLine = FullLine + " " + params[x];
1165         }
1166         for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1167         {
1168                 TreeServer* Route = TreeRoot->GetChild(x);
1169                 if (Route->GetSocket())
1170                 {
1171                         TreeSocket* Sock = Route->GetSocket();
1172                         Sock->WriteLine(FullLine);
1173                 }
1174         }
1175         return true;
1176 }
1177
1178 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target)
1179 {
1180         TreeServer* Route = BestRouteTo(target);
1181         if (Route)
1182         {
1183                 std::string FullLine = ":" + prefix + " " + command;
1184                 for (unsigned int x = 0; x < params.size(); x++)
1185                 {
1186                         FullLine = FullLine + " " + params[x];
1187                 }
1188                 if (Route->GetSocket())
1189                 {
1190                         TreeSocket* Sock = Route->GetSocket();
1191                         Sock->WriteLine(FullLine);
1192                 }
1193                 return true;
1194         }
1195         else
1196         {
1197                 log(DEBUG,"Could not route message with target %s: %s",target.c_str(),command.c_str());
1198                 return true;
1199         }
1200 }
1201
1202
1203 class ModuleSpanningTree : public Module
1204 {
1205         std::vector<TreeSocket*> Bindings;
1206         int line;
1207
1208  public:
1209
1210         void ReadConfiguration(bool rebind)
1211         {
1212                 if (rebind)
1213                 {
1214                         for (int j =0; j < Conf->Enumerate("bind"); j++)
1215                         {
1216                                 std::string Type = Conf->ReadValue("bind","type",j);
1217                                 std::string IP = Conf->ReadValue("bind","address",j);
1218                                 long Port = Conf->ReadInteger("bind","port",j,true);
1219                                 if (Type == "servers")
1220                                 {
1221                                         if (IP == "*")
1222                                         {
1223                                                 IP = "";
1224                                         }
1225                                         TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
1226                                         if (listener->GetState() == I_LISTENING)
1227                                         {
1228                                                 Srv->AddSocket(listener);
1229                                                 Bindings.push_back(listener);
1230                                         }
1231                                         else
1232                                         {
1233                                                 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
1234                                                 listener->Close();
1235                                                 delete listener;
1236                                         }
1237                                 }
1238                         }
1239                 }
1240                 LinkBlocks.clear();
1241                 for (int j =0; j < Conf->Enumerate("link"); j++)
1242                 {
1243                         Link L;
1244                         L.Name = Conf->ReadValue("link","name",j);
1245                         L.IPAddr = Conf->ReadValue("link","ipaddr",j);
1246                         L.Port = Conf->ReadInteger("link","port",j,true);
1247                         L.SendPass = Conf->ReadValue("link","sendpass",j);
1248                         L.RecvPass = Conf->ReadValue("link","recvpass",j);
1249                         LinkBlocks.push_back(L);
1250                         log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
1251                 }
1252         }
1253
1254         ModuleSpanningTree()
1255         {
1256                 Srv = new Server;
1257                 Conf = new ConfigReader;
1258                 Bindings.clear();
1259
1260                 // Create the root of the tree
1261                 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
1262
1263                 ReadConfiguration(true);
1264         }
1265
1266         void ShowLinks(TreeServer* Current, userrec* user, int hops)
1267         {
1268                 std::string Parent = TreeRoot->GetName();
1269                 if (Current->GetParent())
1270                 {
1271                         Parent = Current->GetParent()->GetName();
1272                 }
1273                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1274                 {
1275                         ShowLinks(Current->GetChild(q),user,hops+1);
1276                 }
1277                 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
1278         }
1279
1280         void HandleLinks(char** parameters, int pcnt, userrec* user)
1281         {
1282                 ShowLinks(TreeRoot,user,0);
1283                 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
1284                 return;
1285         }
1286
1287         void HandleLusers(char** parameters, int pcnt, userrec* user)
1288         {
1289                 return;
1290         }
1291
1292         // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
1293
1294         void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
1295         {
1296                 if (line < 128)
1297                 {
1298                         for (int t = 0; t < depth; t++)
1299                         {
1300                                 matrix[line][t] = ' ';
1301                         }
1302                         strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
1303                         line++;
1304                         for (unsigned int q = 0; q < Current->ChildCount(); q++)
1305                         {
1306                                 ShowMap(Current->GetChild(q),user,depth+2,matrix);
1307                         }
1308                 }
1309         }
1310
1311         // Ok, prepare to be confused.
1312         // After much mulling over how to approach this, it struck me that
1313         // the 'usual' way of doing a /MAP isnt the best way. Instead of
1314         // keeping track of a ton of ascii characters, and line by line
1315         // under recursion working out where to place them using multiplications
1316         // and divisons, we instead render the map onto a backplane of characters
1317         // (a character matrix), then draw the branches as a series of "L" shapes
1318         // from the nodes. This is not only friendlier on CPU it uses less stack.
1319
1320         void HandleMap(char** parameters, int pcnt, userrec* user)
1321         {
1322                 // This array represents a virtual screen which we will
1323                 // "scratch" draw to, as the console device of an irc
1324                 // client does not provide for a proper terminal.
1325                 char matrix[128][80];
1326                 for (unsigned int t = 0; t < 128; t++)
1327                 {
1328                         matrix[t][0] = '\0';
1329                 }
1330                 line = 0;
1331                 // The only recursive bit is called here.
1332                 ShowMap(TreeRoot,user,0,matrix);
1333                 // Process each line one by one. The algorithm has a limit of
1334                 // 128 servers (which is far more than a spanning tree should have
1335                 // anyway, so we're ok). This limit can be raised simply by making
1336                 // the character matrix deeper, 128 rows taking 10k of memory.
1337                 for (int l = 1; l < line; l++)
1338                 {
1339                         // scan across the line looking for the start of the
1340                         // servername (the recursive part of the algorithm has placed
1341                         // the servers at indented positions depending on what they
1342                         // are related to)
1343                         int first_nonspace = 0;
1344                         while (matrix[l][first_nonspace] == ' ')
1345                         {
1346                                 first_nonspace++;
1347                         }
1348                         first_nonspace--;
1349                         // Draw the `- (corner) section: this may be overwritten by
1350                         // another L shape passing along the same vertical pane, becoming
1351                         // a |- (branch) section instead.
1352                         matrix[l][first_nonspace] = '-';
1353                         matrix[l][first_nonspace-1] = '`';
1354                         int l2 = l - 1;
1355                         // Draw upwards until we hit the parent server, causing possibly
1356                         // other corners (`-) to become branches (|-)
1357                         while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
1358                         {
1359                                 matrix[l2][first_nonspace-1] = '|';
1360                                 l2--;
1361                         }
1362                 }
1363                 // dump the whole lot to the user. This is the easy bit, honest.
1364                 for (int t = 0; t < line; t++)
1365                 {
1366                         WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
1367                 }
1368                 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
1369                 return;
1370         }
1371
1372         int HandleSquit(char** parameters, int pcnt, userrec* user)
1373         {
1374                 return 1;
1375         }
1376
1377         int HandleConnect(char** parameters, int pcnt, userrec* user)
1378         {
1379                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1380                 {
1381                         if (Srv->MatchText(x->Name.c_str(),parameters[0]))
1382                         {
1383                                 WriteServ(user->fd,"NOTICE %s :*** CONNECT: Connecting to server: %s (%s:%d)",user->nick,x->Name.c_str(),x->IPAddr.c_str(),x->Port);
1384                                 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1385                                 Srv->AddSocket(newsocket);
1386                                 return 1;
1387                         }
1388                 }
1389                 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No matching server could be found in the config file.",user->nick);
1390                 return 1;
1391         }
1392
1393         virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
1394         {
1395                 if (command == "CONNECT")
1396                 {
1397                         return this->HandleConnect(parameters,pcnt,user);
1398                 }
1399                 else if (command == "SQUIT")
1400                 {
1401                         return this->HandleSquit(parameters,pcnt,user);
1402                 }
1403                 else if (command == "MAP")
1404                 {
1405                         this->HandleMap(parameters,pcnt,user);
1406                         return 1;
1407                 }
1408                 else if (command == "LUSERS")
1409                 {
1410                         this->HandleLusers(parameters,pcnt,user);
1411                         return 1;
1412                 }
1413                 else if (command == "LINKS")
1414                 {
1415                         this->HandleLinks(parameters,pcnt,user);
1416                         return 1;
1417                 }
1418                 return 0;
1419         }
1420
1421         virtual void OnGetServerDescription(std::string servername,std::string &description)
1422         {
1423                 TreeServer* s = FindServer(servername);
1424                 if (s)
1425                 {
1426                         description = s->GetDesc();
1427                 }
1428         }
1429
1430         virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
1431         {
1432                 if (std::string(source->server) == Srv->GetServerName())
1433                 {
1434                         std::deque<std::string> params;
1435                         params.push_back(dest->nick);
1436                         params.push_back(channel->name);
1437                         DoOneToMany(source->nick,"INVITE",params);
1438                 }
1439         }
1440
1441         virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
1442         {
1443                 std::deque<std::string> params;
1444                 params.push_back(chan->name);
1445                 params.push_back(":"+topic);
1446                 DoOneToMany(user->nick,"TOPIC",params);
1447         }
1448
1449         virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
1450         {
1451                 if (target_type == TYPE_USER)
1452                 {
1453                         userrec* d = (userrec*)dest;
1454                         if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1455                         {
1456                                 std::deque<std::string> params;
1457                                 params.clear();
1458                                 params.push_back(d->nick);
1459                                 params.push_back(":"+text);
1460                                 DoOneToOne(user->nick,"NOTICE",params,d->server);
1461                         }
1462                 }
1463                 else
1464                 {
1465                         if (std::string(user->server) == Srv->GetServerName())
1466                         {
1467                                 chanrec *c = (chanrec*)dest;
1468                                 std::deque<std::string> params;
1469                                 params.push_back(c->name);
1470                                 params.push_back(":"+text);
1471                                 DoOneToMany(user->nick,"NOTICE",params);
1472                         }
1473                 }
1474         }
1475
1476         virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
1477         {
1478                 if (target_type == TYPE_USER)
1479                 {
1480                         // route private messages which are targetted at clients only to the server
1481                         // which needs to receive them
1482                         userrec* d = (userrec*)dest;
1483                         if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1484                         {
1485                                 std::deque<std::string> params;
1486                                 params.clear();
1487                                 params.push_back(d->nick);
1488                                 params.push_back(":"+text);
1489                                 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
1490                         }
1491                 }
1492                 else
1493                 {
1494                         if (std::string(user->server) == Srv->GetServerName())
1495                         {
1496                                 chanrec *c = (chanrec*)dest;
1497                                 std::deque<std::string> params;
1498                                 params.push_back(c->name);
1499                                 params.push_back(":"+text);
1500                                 DoOneToMany(user->nick,"PRIVMSG",params);
1501                         }
1502                 }
1503         }
1504
1505         virtual void OnUserJoin(userrec* user, chanrec* channel)
1506         {
1507                 // Only do this for local users
1508                 if (std::string(user->server) == Srv->GetServerName())
1509                 {
1510                         log(DEBUG,"**** User on %s JOINS %s",user->server,channel->name);
1511                         std::deque<std::string> params;
1512                         params.clear();
1513                         params.push_back(channel->name);
1514                         if (*channel->key)
1515                         {
1516                                 log(DEBUG,"**** With key %s",channel->key);
1517                                 // if the channel has a key, force the join by emulating the key.
1518                                 params.push_back(channel->key);
1519                         }
1520                         DoOneToMany(user->nick,"JOIN",params);
1521                 }
1522         }
1523
1524         virtual void OnUserPart(userrec* user, chanrec* channel)
1525         {
1526                 if (std::string(user->server) == Srv->GetServerName())
1527                 {
1528                         log(DEBUG,"**** User on %s PARTS %s",user->server,channel->name);
1529                         std::deque<std::string> params;
1530                         params.clear();
1531                         params.push_back(channel->name);
1532                         DoOneToMany(user->nick,"PART",params);
1533                 }
1534         }
1535
1536         virtual void OnUserConnect(userrec* user)
1537         {
1538                 char agestr[MAXBUF];
1539                 if (std::string(user->server) == Srv->GetServerName())
1540                 {
1541                         log(DEBUG,"**** User on %s CONNECTS: %s",user->server,user->nick);
1542                         std::deque<std::string> params;
1543                         snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
1544                         params.clear();
1545                         params.push_back(agestr);
1546                         params.push_back(user->nick);
1547                         params.push_back(user->host);
1548                         params.push_back(user->dhost);
1549                         params.push_back(user->ident);
1550                         params.push_back("+"+std::string(user->modes));
1551                         params.push_back(user->ip);
1552                         params.push_back(":"+std::string(user->fullname));
1553                         DoOneToMany(Srv->GetServerName(),"NICK",params);
1554                 }
1555         }
1556
1557         virtual void OnUserQuit(userrec* user, std::string reason)
1558         {
1559                 if (std::string(user->server) == Srv->GetServerName())
1560                 {
1561                         log(DEBUG,"**** User on %s QUITS: %s",user->server,user->nick);
1562                         std::deque<std::string> params;
1563                         params.push_back(":"+reason);
1564                         DoOneToMany(user->nick,"QUIT",params);
1565                 }
1566         }
1567
1568         virtual void OnUserPostNick(userrec* user, std::string oldnick)
1569         {
1570                 if (std::string(user->server) == Srv->GetServerName())
1571                 {
1572                         log(DEBUG,"**** User on %s changes NICK: %s",user->server,user->nick);
1573                         std::deque<std::string> params;
1574                         params.push_back(user->nick);
1575                         DoOneToMany(oldnick,"NICK",params);
1576                 }
1577         }
1578
1579         virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
1580         {
1581                 if (std::string(source->server) == Srv->GetServerName())
1582                 {
1583                         log(DEBUG,"**** User on %s KICKs: %s %s",source->server,source->nick,user->nick);
1584                         std::deque<std::string> params;
1585                         params.push_back(chan->name);
1586                         params.push_back(user->nick);
1587                         params.push_back(":"+reason);
1588                         DoOneToMany(source->nick,"KICK",params);
1589                 }
1590         }
1591
1592         virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
1593         {
1594                 std::deque<std::string> params;
1595                 params.push_back(dest->nick);
1596                 params.push_back(":"+reason);
1597                 DoOneToMany(source->nick,"KILL",params);
1598         }
1599
1600         virtual void OnRehash(std::string parameter)
1601         {
1602                 if (parameter != "")
1603                 {
1604                         std::deque<std::string> params;
1605                         params.push_back(parameter);
1606                         DoOneToMany(Srv->GetServerName(),"REHASH",params);
1607                         // check for self
1608                         if (Srv->MatchText(Srv->GetServerName(),parameter))
1609                         {
1610                                 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
1611                                 Srv->RehashServer();
1612                         }
1613                 }
1614                 this->ReadConfiguration(false);
1615         }
1616
1617         // note: the protocol does not allow direct umode +o except
1618         // via NICK with 8 params. sending OPERTYPE infers +o modechange
1619         // locally.
1620         virtual void OnOper(userrec* user, std::string opertype)
1621         {
1622                 if (std::string(user->server) == Srv->GetServerName())
1623                 {
1624                         std::deque<std::string> params;
1625                         params.push_back(opertype);
1626                         DoOneToMany(user->nick,"OPERTYPE",params);
1627                 }
1628         }
1629
1630         virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
1631         {
1632                 log(DEBUG,"*** ONMODE TRIGGER");
1633                 if (std::string(user->server) == Srv->GetServerName())
1634                 {
1635                         log(DEBUG,"*** LOCAL");
1636                         if (target_type == TYPE_USER)
1637                         {
1638                                 userrec* u = (userrec*)dest;
1639                                 std::deque<std::string> params;
1640                                 params.push_back(u->nick);
1641                                 params.push_back(text);
1642                                 DoOneToMany(user->nick,"MODE",params);
1643                         }
1644                         else
1645                         {
1646                                 chanrec* c = (chanrec*)dest;
1647                                 std::deque<std::string> params;
1648                                 params.push_back(c->name);
1649                                 params.push_back(text);
1650                                 DoOneToMany(user->nick,"MODE",params);
1651                         }
1652                 }
1653         }
1654
1655         virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
1656         {
1657                 TreeSocket* s = (TreeSocket*)opaque;
1658                 if (target)
1659                 {
1660                         if (target_type == TYPE_USER)
1661                         {
1662                                 userrec* u = (userrec*)target;
1663                                 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
1664                         }
1665                         else
1666                         {
1667                                 chanrec* c = (chanrec*)target;
1668                                 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
1669                         }
1670                 }
1671         }
1672
1673         virtual ~ModuleSpanningTree()
1674         {
1675                 delete Srv;
1676         }
1677
1678         virtual Version GetVersion()
1679         {
1680                 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
1681         }
1682 };
1683
1684
1685 class ModuleSpanningTreeFactory : public ModuleFactory
1686 {
1687  public:
1688         ModuleSpanningTreeFactory()
1689         {
1690         }
1691         
1692         ~ModuleSpanningTreeFactory()
1693         {
1694         }
1695         
1696         virtual Module * CreateModule()
1697         {
1698                 TreeProtocolModule = new ModuleSpanningTree;
1699                 return TreeProtocolModule;
1700         }
1701         
1702 };
1703
1704
1705 extern "C" void * init_module( void )
1706 {
1707         return new ModuleSpanningTreeFactory;
1708 }
1709