]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree.cpp
Fixed a warning
[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                 DoOneToAllButSender(prefix,"SERVER",params,prefix);
629                 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
630                 return true;
631         }
632
633         bool Outbound_Reply_Server(std::deque<std::string> params)
634         {
635                 if (params.size() < 4)
636                         return false;
637                 std::string servername = params[0];
638                 std::string password = params[1];
639                 int hops = atoi(params[2].c_str());
640                 if (hops)
641                 {
642                         this->WriteLine("ERROR :Server too far away for authentication");
643                         return false;
644                 }
645                 std::string description = params[3];
646                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
647                 {
648                         if ((x->Name == servername) && (x->RecvPass == password))
649                         {
650                                 // Begin the sync here. this kickstarts the
651                                 // other side, waiting in WAIT_AUTH_2 state,
652                                 // into starting their burst, as it shows
653                                 // that we're happy.
654                                 this->LinkState = CONNECTED;
655                                 // we should add the details of this server now
656                                 // to the servers tree, as a child of the root
657                                 // node.
658                                 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
659                                 TreeRoot->AddChild(Node);
660                                 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
661                                 this->DoBurst(Node);
662                                 return true;
663                         }
664                 }
665                 this->WriteLine("ERROR :Invalid credentials");
666                 return false;
667         }
668
669         bool Inbound_Server(std::deque<std::string> params)
670         {
671                 if (params.size() < 4)
672                         return false;
673                 std::string servername = params[0];
674                 std::string password = params[1];
675                 int hops = atoi(params[2].c_str());
676                 if (hops)
677                 {
678                         this->WriteLine("ERROR :Server too far away for authentication");
679                         return false;
680                 }
681                 std::string description = params[3];
682                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
683                 {
684                         if ((x->Name == servername) && (x->RecvPass == password))
685                         {
686                                 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
687                                 this->InboundServerName = servername;
688                                 this->InboundDescription = description;
689                                 // this is good. Send our details: Our server name and description and hopcount of 0,
690                                 // along with the sendpass from this block.
691                                 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
692                                 // move to the next state, we are now waiting for THEM.
693                                 this->LinkState = WAIT_AUTH_2;
694                                 return true;
695                         }
696                 }
697                 this->WriteLine("ERROR :Invalid credentials");
698                 return false;
699         }
700
701         std::deque<std::string> Split(std::string line, bool stripcolon)
702         {
703                 std::deque<std::string> n;
704                 std::stringstream s(line);
705                 std::string param = "";
706                 n.clear();
707                 int item = 0;
708                 while (!s.eof())
709                 {
710                         s >> param;
711                         if ((param.c_str()[0] == ':') && (item))
712                         {
713                                 char* str = (char*)param.c_str();
714                                 str++;
715                                 param = str;
716                                 std::string append;
717                                 while (!s.eof())
718                                 {
719                                         append = "";
720                                         s >> append;
721                                         if (append != "")
722                                         {
723                                                 param = param + " " + append;
724                                         }
725                                 }
726                         }
727                         item++;
728                         n.push_back(param);
729                 }
730                 return n;
731         }
732
733         bool ProcessLine(std::string line)
734         {
735                 Srv->Log(DEBUG,"inbound-line: '"+line+"'");
736                 std::deque<std::string> params = this->Split(line,true);
737                 std::string command = "";
738                 std::string prefix = "";
739                 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
740                 {
741                         prefix = params[0];
742                         command = params[1];
743                         char* pref = (char*)prefix.c_str();
744                         prefix = ++pref;
745                         params.pop_front();
746                         params.pop_front();
747                 }
748                 else
749                 {
750                         prefix = "";
751                         command = params[0];
752                         params.pop_front();
753                 }
754                 
755                 switch (this->LinkState)
756                 {
757                         TreeServer* Node;
758                         
759                         case WAIT_AUTH_1:
760                                 // Waiting for SERVER command from remote server. Server initiating
761                                 // the connection sends the first SERVER command, listening server
762                                 // replies with theirs if its happy, then if the initiator is happy,
763                                 // it starts to send its net sync, which starts the merge, otherwise
764                                 // it sends an ERROR.
765                                 if (command == "SERVER")
766                                 {
767                                         return this->Inbound_Server(params);
768                                 }
769                                 else if (command == "ERROR")
770                                 {
771                                         return this->Error(params);
772                                 }
773                         break;
774                         case WAIT_AUTH_2:
775                                 // Waiting for start of other side's netmerge to say they liked our
776                                 // password.
777                                 if (command == "SERVER")
778                                 {
779                                         // cant do this, they sent it to us in the WAIT_AUTH_1 state!
780                                         // silently ignore.
781                                         return true;
782                                 }
783                                 else if (command == "BURST")
784                                 {
785                                         this->LinkState = CONNECTED;
786                                         Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
787                                         TreeRoot->AddChild(Node);
788                                         params.clear();
789                                         params.push_back(InboundServerName);
790                                         params.push_back("*");
791                                         params.push_back("1");
792                                         params.push_back(":"+InboundDescription);
793                                         DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
794                                         this->DoBurst(Node);
795                                 }
796                                 else if (command == "ERROR")
797                                 {
798                                         return this->Error(params);
799                                 }
800                                 
801                         break;
802                         case LISTENER:
803                                 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
804                                 return false;
805                         break;
806                         case CONNECTING:
807                                 if (command == "SERVER")
808                                 {
809                                         // another server we connected to, which was in WAIT_AUTH_1 state,
810                                         // has just sent us their credentials. If we get this far, theyre
811                                         // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
812                                         // if we're happy with this, we should send our netburst which
813                                         // kickstarts the merge.
814                                         return this->Outbound_Reply_Server(params);
815                                 }
816                         break;
817                         case CONNECTED:
818                                 // This is the 'authenticated' state, when all passwords
819                                 // have been exchanged and anything past this point is taken
820                                 // as gospel.
821                                 std::string target = "";
822                                 if ((command == "NICK") && (params.size() > 1))
823                                 {
824                                         return this->IntroduceClient(prefix,params);
825                                 }
826                                 else if (command == "FJOIN")
827                                 {
828                                         return this->ForceJoin(prefix,params);
829                                 }
830                                 else if (command == "SERVER")
831                                 {
832                                         return this->RemoteServer(prefix,params);
833                                 }
834                                 else if (command == "SQUIT")
835                                 {
836                                         if (params.size() == 2)
837                                         {
838                                                 this->Squit(FindServer(params[0]),params[1]);
839                                         }
840                                         return true;
841                                 }
842                                 else
843                                 {
844                                         // not a special inter-server command.
845                                         // Emulate the actual user doing the command,
846                                         // this saves us having a huge ugly parser.
847                                         userrec* who = Srv->FindNick(prefix);
848                                         std::string sourceserv = this->myhost;
849                                         if (this->InboundServerName != "")
850                                         {
851                                                 sourceserv = this->InboundServerName;
852                                         }
853                                         if (who)
854                                         {
855                                                 // its a user
856                                                 target = who->server;
857                                                 char* strparams[127];
858                                                 for (unsigned int q = 0; q < params.size(); q++)
859                                                 {
860                                                         strparams[q] = (char*)params[q].c_str();
861                                                 }
862                                                 log(DEBUG,"*** CALL COMMAND HANDLER FOR %s, SOURCE: '%s'",command.c_str(),who->nick);
863                                                 Srv->CallCommandHandler(command, strparams, params.size(), who);
864                                         }
865                                         else
866                                         {
867                                                 // its not a user. Its either a server, or somethings screwed up.
868                                                 if (IsServer(prefix))
869                                                 {
870                                                         target = Srv->GetServerName();
871                                                 }
872                                                 else
873                                                 {
874                                                         log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
875                                                         return true;
876                                                 }
877                                         }
878                                         return DoOneToAllButSenderRaw(line,sourceserv);
879
880                                 }
881                                 return true;
882                         break;  
883                 }
884                 return true;
885         }
886
887         virtual void OnTimeout()
888         {
889                 if (this->LinkState == CONNECTING)
890                 {
891                         Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
892                 }
893         }
894
895         virtual void OnClose()
896         {
897                 // Connection closed.
898                 // If the connection is fully up (state CONNECTED)
899                 // then propogate a netsplit to all peers.
900                 std::string quitserver = this->myhost;
901                 if (this->InboundServerName != "")
902                 {
903                         quitserver = this->InboundServerName;
904                 }
905                 TreeServer* s = FindServer(quitserver);
906                 if (s)
907                 {
908                         std::deque<std::string> params;
909                         params.push_back(quitserver);
910                         params.push_back(":Remote host closed the connection");
911                         DoOneToAllButSender(Srv->GetServerName(),"SQUIT",params,quitserver);
912                         Squit(s,"Remote host closed the connection");
913                 }
914         }
915
916         virtual int OnIncomingConnection(int newsock, char* ip)
917         {
918                 TreeSocket* s = new TreeSocket(newsock, ip);
919                 Srv->AddSocket(s);
920                 return true;
921         }
922 };
923
924 bool DoOneToAllButSenderRaw(std::string data,std::string omit)
925 {
926         for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
927         {
928                 TreeServer* Route = TreeRoot->GetChild(x);
929                 if ((Route->GetSocket()) && (Route->GetName() != omit) && (BestRouteTo(omit) != Route))
930                 {
931                         TreeSocket* Sock = Route->GetSocket();
932                         log(DEBUG,"Sending RAW to %s",Route->GetName().c_str());
933                         Sock->WriteLine(data);
934                 }
935         }
936         return true;
937 }
938
939 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit)
940 {
941         log(DEBUG,"ALLBUTONE: Comes from %s SHOULD NOT go back to %s",prefix.c_str(),omit.c_str());
942         // TODO: Special stuff with privmsg and notice
943         std::string FullLine = ":" + prefix + " " + command;
944         for (unsigned int x = 0; x < params.size(); x++)
945         {
946                 FullLine = FullLine + " " + params[x];
947         }
948         for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
949         {
950                 TreeServer* Route = TreeRoot->GetChild(x);
951                 // Send the line IF:
952                 // The route has a socket (its a direct connection)
953                 // The route isnt the one to be omitted
954                 // The route isnt the path to the one to be omitted
955                 if ((Route->GetSocket()) && (Route->GetName() != omit) && (BestRouteTo(omit) != Route))
956                 {
957                         TreeSocket* Sock = Route->GetSocket();
958                         log(DEBUG,"Sending to %s",Route->GetName().c_str());
959                         Sock->WriteLine(FullLine);
960                 }
961         }
962         return true;
963 }
964
965 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params)
966 {
967         std::string FullLine = ":" + prefix + " " + command;
968         for (unsigned int x = 0; x < params.size(); x++)
969         {
970                 FullLine = FullLine + " " + params[x];
971         }
972         for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
973         {
974                 TreeServer* Route = TreeRoot->GetChild(x);
975                 if (Route->GetSocket())
976                 {
977                         TreeSocket* Sock = Route->GetSocket();
978                         Sock->WriteLine(FullLine);
979                 }
980         }
981         return true;
982 }
983
984 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target)
985 {
986         TreeServer* Route = BestRouteTo(target);
987         if (Route)
988         {
989                 std::string FullLine = ":" + prefix + " " + command;
990                 for (unsigned int x = 0; x < params.size(); x++)
991                 {
992                         FullLine = FullLine + " " + params[x];
993                 }
994                 if (Route->GetSocket())
995                 {
996                         TreeSocket* Sock = Route->GetSocket();
997                         Sock->WriteLine(FullLine);
998                 }
999                 return true;
1000         }
1001         else
1002         {
1003                 log(DEBUG,"Could not route message with target %s: %s",target.c_str(),command.c_str());
1004                 return true;
1005         }
1006 }
1007
1008
1009 class ModuleSpanningTree : public Module
1010 {
1011         std::vector<TreeSocket*> Bindings;
1012         int line;
1013
1014  public:
1015
1016         void ReadConfiguration(bool rebind)
1017         {
1018                 if (rebind)
1019                 {
1020                         for (int j =0; j < Conf->Enumerate("bind"); j++)
1021                         {
1022                                 std::string Type = Conf->ReadValue("bind","type",j);
1023                                 std::string IP = Conf->ReadValue("bind","address",j);
1024                                 long Port = Conf->ReadInteger("bind","port",j,true);
1025                                 if (Type == "servers")
1026                                 {
1027                                         if (IP == "*")
1028                                         {
1029                                                 IP = "";
1030                                         }
1031                                         TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
1032                                         if (listener->GetState() == I_LISTENING)
1033                                         {
1034                                                 Srv->AddSocket(listener);
1035                                                 Bindings.push_back(listener);
1036                                         }
1037                                         else
1038                                         {
1039                                                 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
1040                                                 listener->Close();
1041                                                 delete listener;
1042                                         }
1043                                 }
1044                         }
1045                 }
1046                 LinkBlocks.clear();
1047                 for (int j =0; j < Conf->Enumerate("link"); j++)
1048                 {
1049                         Link L;
1050                         L.Name = Conf->ReadValue("link","name",j);
1051                         L.IPAddr = Conf->ReadValue("link","ipaddr",j);
1052                         L.Port = Conf->ReadInteger("link","port",j,true);
1053                         L.SendPass = Conf->ReadValue("link","sendpass",j);
1054                         L.RecvPass = Conf->ReadValue("link","recvpass",j);
1055                         LinkBlocks.push_back(L);
1056                         log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
1057                 }
1058         }
1059
1060         ModuleSpanningTree()
1061         {
1062                 Srv = new Server;
1063                 Conf = new ConfigReader;
1064                 Bindings.clear();
1065
1066                 // Create the root of the tree
1067                 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
1068
1069                 ReadConfiguration(true);
1070         }
1071
1072         void ShowLinks(TreeServer* Current, userrec* user, int hops)
1073         {
1074                 std::string Parent = TreeRoot->GetName();
1075                 if (Current->GetParent())
1076                 {
1077                         Parent = Current->GetParent()->GetName();
1078                 }
1079                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1080                 {
1081                         ShowLinks(Current->GetChild(q),user,hops+1);
1082                 }
1083                 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
1084         }
1085
1086         void HandleLinks(char** parameters, int pcnt, userrec* user)
1087         {
1088                 ShowLinks(TreeRoot,user,0);
1089                 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
1090                 return;
1091         }
1092
1093         void HandleLusers(char** parameters, int pcnt, userrec* user)
1094         {
1095                 return;
1096         }
1097
1098         // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
1099
1100         void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
1101         {
1102                 if (line < 128)
1103                 {
1104                         for (int t = 0; t < depth; t++)
1105                         {
1106                                 matrix[line][t] = ' ';
1107                         }
1108                         strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
1109                         line++;
1110                         for (unsigned int q = 0; q < Current->ChildCount(); q++)
1111                         {
1112                                 ShowMap(Current->GetChild(q),user,depth+2,matrix);
1113                         }
1114                 }
1115         }
1116
1117         // Ok, prepare to be confused.
1118         // After much mulling over how to approach this, it struck me that
1119         // the 'usual' way of doing a /MAP isnt the best way. Instead of
1120         // keeping track of a ton of ascii characters, and line by line
1121         // under recursion working out where to place them using multiplications
1122         // and divisons, we instead render the map onto a backplane of characters
1123         // (a character matrix), then draw the branches as a series of "L" shapes
1124         // from the nodes. This is not only friendlier on CPU it uses less stack.
1125
1126         void HandleMap(char** parameters, int pcnt, userrec* user)
1127         {
1128                 // This array represents a virtual screen which we will
1129                 // "scratch" draw to, as the console device of an irc
1130                 // client does not provide for a proper terminal.
1131                 char matrix[128][80];
1132                 for (unsigned int t = 0; t < 128; t++)
1133                 {
1134                         matrix[t][0] = '\0';
1135                 }
1136                 line = 0;
1137                 // The only recursive bit is called here.
1138                 ShowMap(TreeRoot,user,0,matrix);
1139                 // Process each line one by one. The algorithm has a limit of
1140                 // 128 servers (which is far more than a spanning tree should have
1141                 // anyway, so we're ok). This limit can be raised simply by making
1142                 // the character matrix deeper, 128 rows taking 10k of memory.
1143                 for (int l = 1; l < line; l++)
1144                 {
1145                         // scan across the line looking for the start of the
1146                         // servername (the recursive part of the algorithm has placed
1147                         // the servers at indented positions depending on what they
1148                         // are related to)
1149                         int first_nonspace = 0;
1150                         while (matrix[l][first_nonspace] == ' ')
1151                         {
1152                                 first_nonspace++;
1153                         }
1154                         first_nonspace--;
1155                         // Draw the `- (corner) section: this may be overwritten by
1156                         // another L shape passing along the same vertical pane, becoming
1157                         // a |- (branch) section instead.
1158                         matrix[l][first_nonspace] = '-';
1159                         matrix[l][first_nonspace-1] = '`';
1160                         int l2 = l - 1;
1161                         // Draw upwards until we hit the parent server, causing possibly
1162                         // other corners (`-) to become branches (|-)
1163                         while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
1164                         {
1165                                 matrix[l2][first_nonspace-1] = '|';
1166                                 l2--;
1167                         }
1168                 }
1169                 // dump the whole lot to the user. This is the easy bit, honest.
1170                 for (int t = 0; t < line; t++)
1171                 {
1172                         WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
1173                 }
1174                 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
1175                 return;
1176         }
1177
1178         int HandleSquit(char** parameters, int pcnt, userrec* user)
1179         {
1180                 return 1;
1181         }
1182
1183         int HandleConnect(char** parameters, int pcnt, userrec* user)
1184         {
1185                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1186                 {
1187                         if (Srv->MatchText(x->Name.c_str(),parameters[0]))
1188                         {
1189                                 WriteServ(user->fd,"NOTICE %s :*** CONNECT: Connecting to server: %s (%s:%d)",user->nick,x->Name.c_str(),x->IPAddr.c_str(),x->Port);
1190                                 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1191                                 Srv->AddSocket(newsocket);
1192                                 return 1;
1193                         }
1194                 }
1195                 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No matching server could be found in the config file.",user->nick);
1196                 return 1;
1197         }
1198
1199         virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
1200         {
1201                 if (command == "CONNECT")
1202                 {
1203                         return this->HandleConnect(parameters,pcnt,user);
1204                 }
1205                 else if (command == "SQUIT")
1206                 {
1207                         return this->HandleSquit(parameters,pcnt,user);
1208                 }
1209                 else if (command == "MAP")
1210                 {
1211                         this->HandleMap(parameters,pcnt,user);
1212                         return 1;
1213                 }
1214                 else if (command == "LUSERS")
1215                 {
1216                         this->HandleLusers(parameters,pcnt,user);
1217                         return 1;
1218                 }
1219                 else if (command == "LINKS")
1220                 {
1221                         this->HandleLinks(parameters,pcnt,user);
1222                         return 1;
1223                 }
1224                 return 0;
1225         }
1226
1227         virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
1228         {
1229                 if (target_type == TYPE_USER)
1230                 {
1231                         // route private messages which are targetted at clients only to the server
1232                         // which needs to receive them
1233                         userrec* d = (userrec*)dest;
1234                         if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1235                         {
1236                                 std::deque<std::string> params;
1237                                 params.clear();
1238                                 params.push_back(d->nick);
1239                                 params.push_back(":"+text);
1240                                 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
1241                         }
1242                 }
1243                 else
1244                 {
1245                         if (std::string(user->server) == Srv->GetServerName())
1246                         {
1247                                 chanrec *c = (chanrec*)dest;
1248                                 std::deque<std::string> params;
1249                                 params.push_back(c->name);
1250                                 params.push_back(":"+text);
1251                                 DoOneToMany(user->nick,"PRIVMSG",params);
1252                         }
1253                 }
1254         }
1255
1256         virtual void OnUserJoin(userrec* user, chanrec* channel)
1257         {
1258                 // Only do this for local users
1259                 if (std::string(user->server) == Srv->GetServerName())
1260                 {
1261                         log(DEBUG,"**** User on %s JOINS %s",user->server,channel->name);
1262                         std::deque<std::string> params;
1263                         params.clear();
1264                         params.push_back(channel->name);
1265                         if (*channel->key)
1266                         {
1267                                 log(DEBUG,"**** With key %s",channel->key);
1268                                 // if the channel has a key, force the join by emulating the key.
1269                                 params.push_back(channel->key);
1270                         }
1271                         DoOneToMany(user->nick,"JOIN",params);
1272                 }
1273         }
1274
1275         virtual void OnUserPart(userrec* user, chanrec* channel)
1276         {
1277                 if (std::string(user->server) == Srv->GetServerName())
1278                 {
1279                         log(DEBUG,"**** User on %s PARTS %s",user->server,channel->name);
1280                         std::deque<std::string> params;
1281                         params.clear();
1282                         params.push_back(channel->name);
1283                         DoOneToMany(user->nick,"PART",params);
1284                 }
1285         }
1286
1287         virtual ~ModuleSpanningTree()
1288         {
1289                 delete Srv;
1290         }
1291
1292         virtual Version GetVersion()
1293         {
1294                 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
1295         }
1296 };
1297
1298
1299 class ModuleSpanningTreeFactory : public ModuleFactory
1300 {
1301  public:
1302         ModuleSpanningTreeFactory()
1303         {
1304         }
1305         
1306         ~ModuleSpanningTreeFactory()
1307         {
1308         }
1309         
1310         virtual Module * CreateModule()
1311         {
1312                 return new ModuleSpanningTree;
1313         }
1314         
1315 };
1316
1317
1318 extern "C" void * init_module( void )
1319 {
1320         return new ModuleSpanningTreeFactory;
1321 }
1322