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