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