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