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