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