]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree.cpp
Made privmsgs work
[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 bool IsServer(std::string ServerName)
240 {
241         return LookForServer(TreeRoot,ServerName);
242 }
243
244 class TreeSocket : public InspSocket
245 {
246         std::string myhost;
247         std::string in_buffer;
248         ServerState LinkState;
249         std::string InboundServerName;
250         std::string InboundDescription;
251         
252  public:
253
254         TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
255                 : InspSocket(host, port, listening, maxtime)
256         {
257                 Srv->Log(DEBUG,"Create new listening");
258                 myhost = host;
259                 this->LinkState = LISTENER;
260         }
261
262         TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
263                 : InspSocket(host, port, listening, maxtime)
264         {
265                 Srv->Log(DEBUG,"Create new outbound");
266                 myhost = ServerName;
267                 this->LinkState = CONNECTING;
268         }
269
270         TreeSocket(int newfd, char* ip)
271                 : InspSocket(newfd, ip)
272         {
273                 Srv->Log(DEBUG,"Associate new inbound");
274                 this->LinkState = WAIT_AUTH_1;
275         }
276         
277         virtual bool OnConnected()
278         {
279                 if (this->LinkState == CONNECTING)
280                 {
281                         Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
282                         // we should send our details here.
283                         // if the other side is satisfied, they send theirs.
284                         // we do not need to change state here.
285                         for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
286                         {
287                                 if (x->Name == this->myhost)
288                                 {
289                                         // found who we're supposed to be connecting to, send the neccessary gubbins.
290                                         this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
291                                         return true;
292                                 }
293                         }
294                 }
295                 log(DEBUG,"Outbound connection ERROR: Could not find the right link block!");
296                 return true;
297         }
298         
299         virtual void OnError(InspSocketError e)
300         {
301         }
302
303         virtual int OnDisconnect()
304         {
305                 return true;
306         }
307
308         // recursively send the server tree with distances as hops
309         void SendServers(TreeServer* Current, TreeServer* s, int hops)
310         {
311                 char command[1024];
312                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
313                 {
314                         TreeServer* recursive_server = Current->GetChild(q);
315                         if (recursive_server != s)
316                         {
317                                 // :source.server SERVER server.name hops :Description
318                                 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
319                                 this->WriteLine(command);
320                                 // down to next level
321                                 this->SendServers(recursive_server, s, hops+1);
322                         }
323                 }
324         }
325
326         bool IntroduceClient(std::string source, std::deque<std::string> params)
327         {
328                 // NICK age nick host dhost ident +modes ip :gecos
329                 //       0   1    2    3      4     5    6   7
330                 std::string nick = params[1];
331                 std::string host = params[2];
332                 std::string dhost = params[3];
333                 std::string ident = params[4];
334                 time_t age = atoi(params[0].c_str());
335                 std::string modes = params[5];
336                 std::string ip = params[6];
337                 std::string gecos = params[7];
338                 char* tempnick = (char*)nick.c_str();
339                 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
340                 
341                 user_hash::iterator iter;
342                 iter = clientlist.find(tempnick);
343                 if (iter != clientlist.end())
344                 {
345                         // nick collision
346                         log(DEBUG,"Nick collision on %s!%s@%s",tempnick,ident.c_str(),host.c_str());
347                         return true;
348                 }
349                 
350                 clientlist[tempnick] = new userrec();
351                 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
352                 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
353                 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
354                 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
355                 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
356                 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
357                 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
358                 clientlist[tempnick]->registered = 7;
359                 clientlist[tempnick]->signon = age;
360                 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
361                 for (int i = 0; i < MAXCHANS; i++)
362                 {
363                         clientlist[tempnick]->chans[i].channel = NULL;
364                         clientlist[tempnick]->chans[i].uc_modes = 0;
365                 }
366                 DoOneToAllButSender(source,"NICK",params,source);
367                 return true;
368         }
369
370         // send all users and their channels
371         void SendUsers(TreeServer* Current)
372         {
373                 char data[MAXBUF];
374                 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
375                 {
376                         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);
377                         this->WriteLine(data);
378                         if (strchr(u->second->modes,'o'))
379                         {
380                                 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
381                         }
382                         char* chl = chlist(u->second,u->second);
383                         if (*chl)
384                         {
385                                 this->WriteLine(":"+std::string(u->second->nick)+" FJOIN "+std::string(chl));
386                         }
387                 }
388         }
389
390         void DoBurst(TreeServer* s)
391         {
392                 log(DEBUG,"Beginning network burst");
393                 Srv->SendOpers("*** Bursting to "+s->GetName()+".");
394                 this->WriteLine("BURST");
395                 // Send server tree
396                 this->SendServers(TreeRoot,s,1);
397                 // Send users and their channels
398                 this->SendUsers(s);
399                 // TODO: Send everything else (channel modes etc)
400                 this->WriteLine("ENDBURST");
401         }
402
403         virtual bool OnDataReady()
404         {
405                 char* data = this->Read();
406                 if (data)
407                 {
408                         this->in_buffer += data;
409                         while (in_buffer.find("\n") != std::string::npos)
410                         {
411                                 char* line = (char*)in_buffer.c_str();
412                                 std::string ret = "";
413                                 while ((*line != '\n') && (strlen(line)))
414                                 {
415                                         ret = ret + *line;
416                                         line++;
417                                 }
418                                 if ((*line == '\n') || (*line == '\r'))
419                                         line++;
420                                 in_buffer = line;
421                                 if (!this->ProcessLine(ret))
422                                 {
423                                         return false;
424                                 }
425                         }
426                 }
427                 return (data != NULL);
428         }
429
430         int WriteLine(std::string line)
431         {
432                 return this->Write(line + "\r\n");
433         }
434
435         bool Error(std::deque<std::string> params)
436         {
437                 if (params.size() < 1)
438                         return false;
439                 std::string Errmsg = params[0];
440                 std::string SName = myhost;
441                 if (InboundServerName != "")
442                 {
443                         SName = InboundServerName;
444                 }
445                 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
446                 // we will return false to cause the socket to close.
447                 return false;
448         }
449
450         bool Outbound_Reply_Server(std::deque<std::string> params)
451         {
452                 if (params.size() < 4)
453                         return false;
454                 std::string servername = params[0];
455                 std::string password = params[1];
456                 int hops = atoi(params[2].c_str());
457                 if (hops)
458                 {
459                         this->WriteLine("ERROR :Server too far away for authentication");
460                         return false;
461                 }
462                 std::string description = params[3];
463                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
464                 {
465                         if ((x->Name == servername) && (x->RecvPass == password))
466                         {
467                                 // Begin the sync here. this kickstarts the
468                                 // other side, waiting in WAIT_AUTH_2 state,
469                                 // into starting their burst, as it shows
470                                 // that we're happy.
471                                 this->LinkState = CONNECTED;
472                                 // we should add the details of this server now
473                                 // to the servers tree, as a child of the root
474                                 // node.
475                                 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
476                                 TreeRoot->AddChild(Node);
477                                 this->DoBurst(Node);
478                                 return true;
479                         }
480                 }
481                 this->WriteLine("ERROR :Invalid credentials");
482                 return false;
483         }
484
485         bool Inbound_Server(std::deque<std::string> params)
486         {
487                 if (params.size() < 4)
488                         return false;
489                 std::string servername = params[0];
490                 std::string password = params[1];
491                 int hops = atoi(params[2].c_str());
492                 if (hops)
493                 {
494                         this->WriteLine("ERROR :Server too far away for authentication");
495                         return false;
496                 }
497                 std::string description = params[3];
498                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
499                 {
500                         if ((x->Name == servername) && (x->RecvPass == password))
501                         {
502                                 Srv->SendOpers("*** Verified incoming server connection from "+servername+"["+this->GetIP()+"] ("+description+")");
503                                 this->InboundServerName = servername;
504                                 this->InboundDescription = description;
505                                 // this is good. Send our details: Our server name and description and hopcount of 0,
506                                 // along with the sendpass from this block.
507                                 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
508                                 // move to the next state, we are now waiting for THEM.
509                                 this->LinkState = WAIT_AUTH_2;
510                                 return true;
511                         }
512                 }
513                 this->WriteLine("ERROR :Invalid credentials");
514                 return false;
515         }
516
517         std::deque<std::string> Split(std::string line)
518         {
519                 std::deque<std::string> n;
520                 std::stringstream s(line);
521                 std::string param = "";
522                 n.clear();
523                 int item = 0;
524                 while (!s.eof())
525                 {
526                         s >> param;
527                         if ((param.c_str()[0] == ':') && (item))
528                         {
529                                 char* str = (char*)param.c_str();
530                                 str++;
531                                 param = str;
532                                 std::string append;
533                                 while (!s.eof())
534                                 {
535                                         append = "";
536                                         s >> append;
537                                         if (append != "")
538                                         {
539                                                 param = param + " " + append;
540                                         }
541                                 }
542                         }
543                         item++;
544                         n.push_back(param);
545                 }
546                 return n;
547         }
548
549         bool ProcessLine(std::string line)
550         {
551                 Srv->SendToModeMask("o",WM_AND,"inbound-line: '"+line+"'");
552
553                 std::deque<std::string> params = this->Split(line);
554                 std::string command = "";
555                 std::string prefix = "";
556                 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
557                 {
558                         prefix = params[0];
559                         command = params[1];
560                         char* pref = (char*)prefix.c_str();
561                         prefix = ++pref;
562                         params.pop_front();
563                         params.pop_front();
564                 }
565                 else
566                 {
567                         prefix = "";
568                         command = params[0];
569                         params.pop_front();
570                 }
571                 
572                 switch (this->LinkState)
573                 {
574                         TreeServer* Node;
575                         
576                         case WAIT_AUTH_1:
577                                 // Waiting for SERVER command from remote server. Server initiating
578                                 // the connection sends the first SERVER command, listening server
579                                 // replies with theirs if its happy, then if the initiator is happy,
580                                 // it starts to send its net sync, which starts the merge, otherwise
581                                 // it sends an ERROR.
582                                 if (command == "SERVER")
583                                 {
584                                         return this->Inbound_Server(params);
585                                 }
586                                 else if (command == "ERROR")
587                                 {
588                                         return this->Error(params);
589                                 }
590                         break;
591                         case WAIT_AUTH_2:
592                                 // Waiting for start of other side's netmerge to say they liked our
593                                 // password.
594                                 if (command == "SERVER")
595                                 {
596                                         // cant do this, they sent it to us in the WAIT_AUTH_1 state!
597                                         // silently ignore.
598                                         return true;
599                                 }
600                                 else if (command == "BURST")
601                                 {
602                                         this->LinkState = CONNECTED;
603                                         Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
604                                         TreeRoot->AddChild(Node);
605                                         this->DoBurst(Node);
606                                 }
607                                 else if (command == "ERROR")
608                                 {
609                                         return this->Error(params);
610                                 }
611                                 
612                         break;
613                         case LISTENER:
614                                 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
615                                 return false;
616                         break;
617                         case CONNECTING:
618                                 if (command == "SERVER")
619                                 {
620                                         // another server we connected to, which was in WAIT_AUTH_1 state,
621                                         // has just sent us their credentials. If we get this far, theyre
622                                         // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
623                                         // if we're happy with this, we should send our netburst which
624                                         // kickstarts the merge.
625                                         return this->Outbound_Reply_Server(params);
626                                 }
627                         break;
628                         case CONNECTED:
629                                 // This is the 'authenticated' state, when all passwords
630                                 // have been exchanged and anything past this point is taken
631                                 // as gospel.
632                                 std::string target = "";
633                                 if ((command == "NICK") && (params.size() > 1))
634                                 {
635                                         return this->IntroduceClient(prefix,params);
636                                 }
637                                 else
638                                 {
639                                         // not a special inter-server command.
640                                         // Emulate the actual user doing the command,
641                                         // this saves us having a huge ugly parser.
642                                         userrec* who = Srv->FindNick(prefix);
643                                         std::string sourceserv = this->myhost;
644                                         if (this->InboundServerName != "")
645                                         {
646                                                 sourceserv = this->InboundServerName;
647                                         }
648                                         if (who)
649                                         {
650                                                 // its a user
651                                                 target = who->server;
652                                                 char* strparams[127];
653                                                 for (unsigned int q = 0; q < params.size(); q++)
654                                                 {
655                                                         strparams[q] = (char*)params[q].c_str();
656                                                 }
657                                                 log(DEBUG,"*** CALL COMMAND HANDLER FOR %s, SOURCE: '%s'",command.c_str(),who->nick);
658                                                 Srv->CallCommandHandler(command, strparams, params.size(), who);
659                                         }
660                                         else
661                                         {
662                                                 // its not a user. Its either a server, or somethings screwed up.
663                                                 if (IsServer(prefix))
664                                                 {
665                                                         target = Srv->GetServerName();
666                                                 }
667                                                 else
668                                                 {
669                                                         log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
670                                                         return true;
671                                                 }
672                                         }
673                                         return DoOneToAllButSender(prefix,command,params,sourceserv);
674
675                                 }
676                                 return true;
677                         break;  
678                 }
679                 return true;
680         }
681
682         virtual void OnTimeout()
683         {
684                 if (this->LinkState = CONNECTING)
685                 {
686                         Srv->SendOpers("*** CONNECT: Connection to "+myhost+" timed out.");
687                 }
688         }
689
690         virtual void OnClose()
691         {
692         }
693
694         virtual int OnIncomingConnection(int newsock, char* ip)
695         {
696                 TreeSocket* s = new TreeSocket(newsock, ip);
697                 Srv->AddSocket(s);
698                 return true;
699         }
700 };
701
702 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit)
703 {
704         // TODO: Special stuff with privmsg and notice
705         std::string FullLine = ":" + prefix + " " + command;
706         for (unsigned int x = 0; x < params.size(); x++)
707         {
708                 FullLine = FullLine + " " + params[x];
709         }
710         for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
711         {
712                 TreeServer* Route = TreeRoot->GetChild(x);
713                 if ((Route->GetSocket()) && (Route->GetName() != omit))
714                 {
715                         TreeSocket* Sock = Route->GetSocket();
716                         Sock->WriteLine(FullLine);
717                 }
718         }
719         return true;
720 }
721
722 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params)
723 {
724         std::string FullLine = ":" + prefix + " " + command;
725         for (unsigned int x = 0; x < params.size(); x++)
726         {
727                 FullLine = FullLine + " " + params[x];
728         }
729         for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
730         {
731                 TreeServer* Route = TreeRoot->GetChild(x);
732                 if (Route->GetSocket())
733                 {
734                         TreeSocket* Sock = Route->GetSocket();
735                         Sock->WriteLine(FullLine);
736                 }
737         }
738         return true;
739 }
740
741 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target)
742 {
743         TreeServer* Route = BestRouteTo(target);
744         if (Route)
745         {
746                 std::string FullLine = ":" + prefix + " " + command;
747                 for (unsigned int x = 0; x < params.size(); x++)
748                 {
749                         FullLine = FullLine + " " + params[x];
750                 }
751                 if (Route->GetSocket())
752                 {
753                         TreeSocket* Sock = Route->GetSocket();
754                         Sock->WriteLine(FullLine);
755                 }
756                 return true;
757         }
758         else
759         {
760                 log(DEBUG,"Could not route message with target %s: %s",target.c_str(),command.c_str());
761                 return true;
762         }
763 }
764
765
766 class ModuleSpanningTree : public Module
767 {
768         std::vector<TreeSocket*> Bindings;
769
770  public:
771
772         void ReadConfiguration(bool rebind)
773         {
774                 if (rebind)
775                 {
776                         for (int j =0; j < Conf->Enumerate("bind"); j++)
777                         {
778                                 std::string Type = Conf->ReadValue("bind","type",j);
779                                 std::string IP = Conf->ReadValue("bind","address",j);
780                                 long Port = Conf->ReadInteger("bind","port",j,true);
781                                 if (Type == "servers")
782                                 {
783                                         if (IP == "*")
784                                         {
785                                                 IP = "";
786                                         }
787                                         TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
788                                         if (listener->GetState() == I_LISTENING)
789                                         {
790                                                 Srv->AddSocket(listener);
791                                                 Bindings.push_back(listener);
792                                         }
793                                         else
794                                         {
795                                                 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
796                                                 listener->Close();
797                                                 delete listener;
798                                         }
799                                 }
800                         }
801                 }
802                 LinkBlocks.clear();
803                 for (int j =0; j < Conf->Enumerate("link"); j++)
804                 {
805                         Link L;
806                         L.Name = Conf->ReadValue("link","name",j);
807                         L.IPAddr = Conf->ReadValue("link","ipaddr",j);
808                         L.Port = Conf->ReadInteger("link","port",j,true);
809                         L.SendPass = Conf->ReadValue("link","sendpass",j);
810                         L.RecvPass = Conf->ReadValue("link","recvpass",j);
811                         LinkBlocks.push_back(L);
812                         log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
813                 }
814         }
815
816         ModuleSpanningTree()
817         {
818                 Srv = new Server;
819                 Conf = new ConfigReader;
820                 Bindings.clear();
821
822                 // Create the root of the tree
823                 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
824
825                 ReadConfiguration(true);
826         }
827
828         void HandleLinks(char** parameters, int pcnt, userrec* user)
829         {
830                 return;
831         }
832
833         void HandleLusers(char** parameters, int pcnt, userrec* user)
834         {
835                 return;
836         }
837
838         void HandleMap(char** parameters, int pcnt, userrec* user)
839         {
840                 return;
841         }
842
843         int HandleSquit(char** parameters, int pcnt, userrec* user)
844         {
845                 return 1;
846         }
847
848         int HandleConnect(char** parameters, int pcnt, userrec* user)
849         {
850                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
851                 {
852                         if (Srv->MatchText(x->Name.c_str(),parameters[0]))
853                         {
854                                 WriteServ(user->fd,"NOTICE %s :*** CONNECT: Connecting to server: %s (%s:%d)",user->nick,x->Name.c_str(),x->IPAddr.c_str(),x->Port);
855                                 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
856                                 Srv->AddSocket(newsocket);
857                                 return 1;
858                         }
859                 }
860                 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No matching server could be found in the config file.",user->nick);
861                 return 1;
862         }
863
864         virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
865         {
866                 if (command == "CONNECT")
867                 {
868                         return this->HandleConnect(parameters,pcnt,user);
869                 }
870                 else if (command == "SQUIT")
871                 {
872                         return this->HandleSquit(parameters,pcnt,user);
873                 }
874                 else if (command == "MAP")
875                 {
876                         this->HandleMap(parameters,pcnt,user);
877                         return 1;
878                 }
879                 else if (command == "LUSERS")
880                 {
881                         this->HandleLusers(parameters,pcnt,user);
882                         return 1;
883                 }
884                 else if (command == "LINKS")
885                 {
886                         this->HandleLinks(parameters,pcnt,user);
887                         return 1;
888                 }
889                 return 0;
890         }
891
892         virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
893         {
894                 if (target_type == TYPE_USER)
895                 {
896                         // route private messages which are targetted at clients only to the server
897                         // which needs to receive them
898                         userrec* d = (userrec*)dest;
899                         if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
900                         {
901                                 std::deque<std::string> params;
902                                 params.clear();
903                                 params.push_back(d->nick);
904                                 params.push_back(":"+text);
905                                 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
906                         }
907                 }
908         }
909
910         virtual void OnUserJoin(userrec* user, chanrec* channel)
911         {
912                 // Only do this for local users
913                 if (std::string(user->server) == Srv->GetServerName())
914                 {
915                         log(DEBUG,"**** User on %s JOINS %s",user->server,channel->name);
916                         std::deque<std::string> params;
917                         params.clear();
918                         params.push_back(channel->name);
919                         if (*channel->key)
920                         {
921                                 log(DEBUG,"**** With key %s",channel->key);
922                                 // if the channel has a key, force the join by emulating the key.
923                                 params.push_back(channel->key);
924                         }
925                         DoOneToMany(user->nick,"JOIN",params);
926                 }
927         }
928
929         virtual ~ModuleSpanningTree()
930         {
931                 delete Srv;
932         }
933
934         virtual Version GetVersion()
935         {
936                 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
937         }
938 };
939
940
941 class ModuleSpanningTreeFactory : public ModuleFactory
942 {
943  public:
944         ModuleSpanningTreeFactory()
945         {
946         }
947         
948         ~ModuleSpanningTreeFactory()
949         {
950         }
951         
952         virtual Module * CreateModule()
953         {
954                 return new ModuleSpanningTree;
955         }
956         
957 };
958
959
960 extern "C" void * init_module( void )
961 {
962         return new ModuleSpanningTreeFactory;
963 }
964