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