]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree.cpp
Added experimental channel TS
[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 class ModuleSpanningTree;
46 static ModuleSpanningTree* TreeProtocolModule;
47
48 extern std::vector<Module*> modules;
49 extern std::vector<ircd_module*> factory;
50 extern int MODCOUNT;
51
52 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
53
54 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
55 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;
56
57 extern user_hash clientlist;
58 extern chan_hash chanlist;
59
60 class TreeServer;
61 class TreeSocket;
62
63 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target);
64 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit);
65 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params);
66 bool DoOneToAllButSenderRaw(std::string data,std::string omit, std::string prefix,std::string command,std::deque<std::string> params);
67 void ReadConfiguration(bool rebind);
68
69 class TreeServer
70 {
71         TreeServer* Parent;
72         std::vector<TreeServer*> Children;
73         std::string ServerName;
74         std::string ServerDesc;
75         std::string VersionString;
76         int UserCount;
77         int OperCount;
78         TreeSocket* Socket;     // for directly connected servers this points at the socket object
79         
80  public:
81
82         TreeServer()
83         {
84                 Parent = NULL;
85                 ServerName = "";
86                 ServerDesc = "";
87                 VersionString = "";
88                 UserCount = OperCount = 0;
89         }
90
91         TreeServer(std::string Name, std::string Desc) : ServerName(Name), ServerDesc(Desc)
92         {
93                 Parent = NULL;
94                 VersionString = "";
95                 UserCount = OperCount = 0;
96         }
97
98         TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name), ServerDesc(Desc), Socket(Sock)
99         {
100                 VersionString = "";
101                 UserCount = OperCount = 0;
102         }
103
104         std::string GetName()
105         {
106                 return this->ServerName;
107         }
108
109         std::string GetDesc()
110         {
111                 return this->ServerDesc;
112         }
113
114         std::string GetVersion()
115         {
116                 return this->VersionString;
117         }
118
119         int GetUserCount()
120         {
121                 return this->UserCount;
122         }
123
124         int GetOperCount()
125         {
126                 return this->OperCount;
127         }
128
129         TreeSocket* GetSocket()
130         {
131                 return this->Socket;
132         }
133
134         TreeServer* GetParent()
135         {
136                 return this->Parent;
137         }
138
139         unsigned int ChildCount()
140         {
141                 return Children.size();
142         }
143
144         TreeServer* GetChild(unsigned int n)
145         {
146                 if (n < Children.size())
147                 {
148                         return Children[n];
149                 }
150                 else
151                 {
152                         return NULL;
153                 }
154         }
155
156         void AddChild(TreeServer* Child)
157         {
158                 Children.push_back(Child);
159         }
160
161         bool DelChild(TreeServer* Child)
162         {
163                 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
164                 {
165                         if (*a == Child)
166                         {
167                                 Children.erase(a);
168                                 return true;
169                         }
170                 }
171                 return false;
172         }
173
174         // removes child nodes of this node, and of that node, etc etc
175         bool Tidy()
176         {
177                 bool stillchildren = true;
178                 while (stillchildren)
179                 {
180                         stillchildren = false;
181                         for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
182                         {
183                                 TreeServer* s = (TreeServer*)*a;
184                                 s->Tidy();
185                                 Children.erase(a);
186                                 delete s;
187                                 stillchildren = true;
188                                 break;
189                         }
190                 }
191                 return true;
192         }
193 };
194
195 class Link
196 {
197  public:
198          std::string Name;
199          std::string IPAddr;
200          int Port;
201          std::string SendPass;
202          std::string RecvPass;
203 };
204
205 /* $ModDesc: Povides a spanning tree server link protocol */
206
207 Server *Srv;
208 ConfigReader *Conf;
209 TreeServer *TreeRoot;
210 std::vector<Link> LinkBlocks;
211
212 TreeServer* RouteEnumerate(TreeServer* Current, std::string ServerName)
213 {
214         if (Current->GetName() == ServerName)
215                 return Current;
216         for (unsigned int q = 0; q < Current->ChildCount(); q++)
217         {
218                 TreeServer* found = RouteEnumerate(Current->GetChild(q),ServerName);
219                 if (found)
220                 {
221                         return found;
222                 }
223         }
224         return NULL;
225 }
226
227 // Returns the locally connected server we must route a
228 // message through to reach server 'ServerName'. This
229 // only applies to one-to-one and not one-to-many routing.
230 TreeServer* BestRouteTo(std::string ServerName)
231 {
232         if (ServerName.c_str() == TreeRoot->GetName())
233         {
234                 return NULL;
235         }
236         // first, find the server by recursively walking the tree
237         TreeServer* Found = RouteEnumerate(TreeRoot,ServerName);
238         // did we find it? If not, they did something wrong, abort.
239         if (!Found)
240         {
241                 return NULL;
242         }
243         else
244         {
245                 // The server exists, follow its parent nodes until
246                 // the parent of the current is 'TreeRoot', we know
247                 // then that this is a directly-connected server.
248                 while ((Found) && (Found->GetParent() != TreeRoot))
249                 {
250                         Found = Found->GetParent();
251                 }
252                 return Found;
253         }
254 }
255
256 bool LookForServer(TreeServer* Current, std::string ServerName)
257 {
258         if (ServerName == Current->GetName())
259                 return true;
260         for (unsigned int q = 0; q < Current->ChildCount(); q++)
261         {
262                 if (LookForServer(Current->GetChild(q),ServerName))
263                         return true;
264         }
265         return false;
266 }
267
268 TreeServer* Found;
269
270 void RFindServer(TreeServer* Current, std::string ServerName)
271 {
272         if ((ServerName == Current->GetName()) && (!Found))
273         {
274                 Found = Current;
275                 return;
276         }
277         if (!Found)
278         {
279                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
280                 {
281                         if (!Found)
282                                 RFindServer(Current->GetChild(q),ServerName);
283                 }
284         }
285         return;
286 }
287
288 TreeServer* FindServer(std::string ServerName)
289 {
290         Found = NULL;
291         RFindServer(TreeRoot,ServerName);
292         return Found;
293 }
294
295 bool IsServer(std::string ServerName)
296 {
297         return LookForServer(TreeRoot,ServerName);
298 }
299
300 class TreeSocket : public InspSocket
301 {
302         std::string myhost;
303         std::string in_buffer;
304         ServerState LinkState;
305         std::string InboundServerName;
306         std::string InboundDescription;
307         int num_lost_users;
308         int num_lost_servers;
309         
310  public:
311
312         TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
313                 : InspSocket(host, port, listening, maxtime)
314         {
315                 myhost = host;
316                 this->LinkState = LISTENER;
317         }
318
319         TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
320                 : InspSocket(host, port, listening, maxtime)
321         {
322                 myhost = ServerName;
323                 this->LinkState = CONNECTING;
324         }
325
326         TreeSocket(int newfd, char* ip)
327                 : InspSocket(newfd, ip)
328         {
329                 this->LinkState = WAIT_AUTH_1;
330         }
331         
332         virtual bool OnConnected()
333         {
334                 if (this->LinkState == CONNECTING)
335                 {
336                         Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
337                         // we should send our details here.
338                         // if the other side is satisfied, they send theirs.
339                         // we do not need to change state here.
340                         for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
341                         {
342                                 if (x->Name == this->myhost)
343                                 {
344                                         // found who we're supposed to be connecting to, send the neccessary gubbins.
345                                         this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
346                                         return true;
347                                 }
348                         }
349                 }
350                 return true;
351         }
352         
353         virtual void OnError(InspSocketError e)
354         {
355         }
356
357         virtual int OnDisconnect()
358         {
359                 return true;
360         }
361
362         // recursively send the server tree with distances as hops
363         void SendServers(TreeServer* Current, TreeServer* s, int hops)
364         {
365                 char command[1024];
366                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
367                 {
368                         TreeServer* recursive_server = Current->GetChild(q);
369                         if (recursive_server != s)
370                         {
371                                 // :source.server SERVER server.name hops :Description
372                                 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
373                                 this->WriteLine(command);
374                                 // down to next level
375                                 this->SendServers(recursive_server, s, hops+1);
376                         }
377                 }
378         }
379
380         void SquitServer(TreeServer* Current)
381         {
382                 // recursively squit the servers attached to 'Current'
383                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
384                 {
385                         TreeServer* recursive_server = Current->GetChild(q);
386                         this->SquitServer(recursive_server);
387                 }
388                 // Now we've whacked the kids, whack self
389                 num_lost_servers++;
390                 bool quittingpeople = true;
391                 while (quittingpeople)
392                 {
393                         quittingpeople = false;
394                         for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
395                         {
396                                 if (!strcasecmp(u->second->server,Current->GetName().c_str()))
397                                 {
398                                         Srv->QuitUser(u->second,Current->GetName()+" "+std::string(Srv->GetServerName()));
399                                         num_lost_users++;
400                                         quittingpeople = true;
401                                         break;
402                                 }
403                         }
404                 }
405         }
406
407         void Squit(TreeServer* Current,std::string reason)
408         {
409                 if (Current)
410                 {
411                         std::deque<std::string> params;
412                         params.push_back(Current->GetName());
413                         params.push_back(":"+reason);
414                         DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
415                         if (Current->GetParent() == TreeRoot)
416                         {
417                                 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
418                         }
419                         else
420                         {
421                                 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
422                         }
423                         num_lost_servers = 0;
424                         num_lost_users = 0;
425                         SquitServer(Current);
426                         Current->Tidy();
427                         Current->GetParent()->DelChild(Current);
428                         delete Current;
429                         WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
430                 }
431                 else
432                 {
433                         log(DEFAULT,"Squit from unknown server");
434                 }
435         }
436
437         bool ForceMode(std::string source, std::deque<std::string> params)
438         {
439                 userrec* who = new userrec;
440                 who->fd = FD_MAGIC_NUMBER;
441                 if (params.size() < 2)
442                         return true;
443                 char* modelist[255];
444                 for (unsigned int q = 0; q < params.size(); q++)
445                 {
446                         modelist[q] = (char*)params[q].c_str();
447                 }
448                 Srv->SendMode(modelist,params.size(),who);
449                 DoOneToAllButSender(source,"FMODE",params,source);
450                 delete who;
451                 return true;
452         }
453
454         bool ForceTopic(std::string source, std::deque<std::string> params)
455         {
456                 // FTOPIC %s %lu %s :%s
457                 if (params.size() != 4)
458                         return true;
459                 std::string channel = params[0];
460                 time_t ts = atoi(params[1].c_str());
461                 std::string setby = params[2];
462                 std::string topic = params[3];
463
464                 chanrec* c = Srv->FindChannel(channel);
465                 if (c)
466                 {
467                         if ((ts >= c->topicset) || (!*c->topic))
468                         {
469                                 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
470                                 strlcpy(c->setby,setby.c_str(),NICKMAX);
471                                 c->topicset = ts;
472                                 WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
473                         }
474                         
475                 }
476                 
477                 // all done, send it on its way
478                 params[3] = ":" + params[3];
479                 DoOneToAllButSender(source,"FTOPIC",params,source);
480
481                 return true;
482         }
483
484         bool ForceJoin(std::string source, std::deque<std::string> params)
485         {
486                 if (params.size() < 3)
487                         return true;
488
489                 char first[MAXBUF];
490                 char modestring[MAXBUF];
491                 char* mode_users[127];
492                 mode_users[0] = first;
493                 mode_users[1] = modestring;
494                 strcpy(mode_users[1],"+");
495                 unsigned int modectr = 2;
496                 
497                 userrec* who = NULL;
498                 std::string channel = params[0];
499                 time_t TS = atoi(params[1].c_str());
500                 char* key = "";
501                 
502                 chanrec* chan = Srv->FindChannel(channel);
503                 if (chan)
504                 {
505                         key = chan->key;
506                 }
507                 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
508
509                 // default is a high value, which if we dont have this
510                 // channel will let the other side apply their modes.
511                 time_t ourTS = time(NULL)+20;
512                 chanrec* us = Srv->FindChannel(channel);
513                 if (us)
514                 {
515                         ourTS = us->age;
516                 }
517
518                 log(DEBUG,"FJOIN detected, our TS=%lu, their TS=%lu",ourTS,TS);
519                 
520                 for (unsigned int usernum = 2; usernum < params.size(); usernum++)
521                 {
522                         // process one channel at a time, applying modes.
523                         char* usr = (char*)params[usernum].c_str();
524                         char permissions = *usr;
525                         switch (permissions)
526                         {
527                                 case '@':
528                                         usr++;
529                                         mode_users[modectr++] = usr;
530                                         strlcat(modestring,"o",MAXBUF);
531                                 break;
532                                 case '%':
533                                         usr++;
534                                         mode_users[modectr++] = usr;
535                                         strlcat(modestring,"h",MAXBUF);
536                                 break;
537                                 case '+':
538                                         usr++;
539                                         mode_users[modectr++] = usr;
540                                         strlcat(modestring,"v",MAXBUF);
541                                 break;
542                         }
543                         who = Srv->FindNick(usr);
544                         if (who)
545                         {
546                                 Srv->JoinUserToChannel(who,channel,key);
547                                 if (modectr >= (MAXMODES-1))
548                                 {
549                                         // theres a mode for this user. push them onto the mode queue, and flush it
550                                         // if there are more than MAXMODES to go.
551                                         if (ourTS >= TS)
552                                         {
553                                                 log(DEBUG,"Our our channel newer than theirs, accepting their modes");
554                                                 Srv->SendMode(mode_users,modectr,who);
555                                         }
556                                         else
557                                         {
558                                                 log(DEBUG,"Their channel newer than ours, bouncing their modes");
559                                                 // bouncy bouncy!
560                                                 std::deque<std::string> params;
561                                                 params.push_back(channel);
562                                                 // modes are now being UNSET...
563                                                 *mode_users[1] = '-';
564                                                 for (unsigned int x = 0; x < modectr; x++)
565                                                 {
566                                                         params.push_back(mode_users[x]);
567                                                 }
568                                                 // tell everyone to bounce the modes. bad modes, bad!
569                                                 DoOneToMany(Srv->GetServerName(),"FMODE",params);
570                                         }
571                                         strcpy(mode_users[1],"+");
572                                         modectr = 2;
573                                 }
574                         }
575                 }
576                 // there werent enough modes built up to flush it during FJOIN,
577                 // or, there are a number left over. flush them out.
578                 if ((modectr > 2) && (who))
579                 {
580                         if (ourTS >= TS)
581                         {
582                                 Srv->SendMode(mode_users,modectr,who);
583                         }
584                         else
585                         {
586                                 std::deque<std::string> params;
587                                 params.push_back(channel);
588                                 *mode_users[1] = '-';
589                                 for (unsigned int x = 0; x < modectr; x++)
590                                 {
591                                         params.push_back(mode_users[x]);
592                                 }
593                                 DoOneToMany(Srv->GetServerName(),"FMODE",params);
594                         }
595                 }
596                 // sync the TS
597                 us = Srv->FindChannel(channel);
598                 if (us)
599                 {
600                         us->age = TS;
601                 }
602                 DoOneToAllButSender(source,"FJOIN",params,source);
603                 return true;
604         }
605
606         bool IntroduceClient(std::string source, std::deque<std::string> params)
607         {
608                 if (params.size() < 8)
609                         return true;
610                 // NICK age nick host dhost ident +modes ip :gecos
611                 //       0   1    2    3      4     5    6   7
612                 std::string nick = params[1];
613                 std::string host = params[2];
614                 std::string dhost = params[3];
615                 std::string ident = params[4];
616                 time_t age = atoi(params[0].c_str());
617                 std::string modes = params[5];
618                 if (*(modes.c_str()) == '+')
619                 {
620                         char* m = (char*)modes.c_str();
621                         m++;
622                         modes = m;
623                 }
624                 std::string ip = params[6];
625                 std::string gecos = params[7];
626                 char* tempnick = (char*)nick.c_str();
627                 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
628                 
629                 user_hash::iterator iter;
630                 iter = clientlist.find(tempnick);
631                 if (iter != clientlist.end())
632                 {
633                         // nick collision
634                         log(DEBUG,"Nick collision on %s!%s@%s: %lu %lu",tempnick,ident.c_str(),host.c_str(),(unsigned long)age,(unsigned long)iter->second->age);
635                         this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Nickname collision");
636                         return true;
637                 }
638
639                 clientlist[tempnick] = new userrec();
640                 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
641                 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
642                 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
643                 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
644                 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
645                 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
646                 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
647                 clientlist[tempnick]->registered = 7;
648                 clientlist[tempnick]->signon = age;
649                 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
650                 for (int i = 0; i < MAXCHANS; i++)
651                 {
652                         clientlist[tempnick]->chans[i].channel = NULL;
653                         clientlist[tempnick]->chans[i].uc_modes = 0;
654                 }
655                 params[7] = ":" + params[7];
656                 DoOneToAllButSender(source,"NICK",params,source);
657                 return true;
658         }
659
660         void SendFJoins(TreeServer* Current, chanrec* c)
661         {
662                 char list[MAXBUF];
663                 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
664                 std::vector<char*> *ulist = c->GetUsers();
665                 for (unsigned int i = 0; i < ulist->size(); i++)
666                 {
667                         char* o = (*ulist)[i];
668                         userrec* otheruser = (userrec*)o;
669                         strlcat(list," ",MAXBUF);
670                         strlcat(list,cmode(otheruser,c),MAXBUF);
671                         strlcat(list,otheruser->nick,MAXBUF);
672                         if (strlen(list)>(480-NICKMAX))
673                         {
674                                 this->WriteLine(list);
675                                 snprintf(list,MAXBUF,":%s FJOIN %s %lu",Srv->GetServerName().c_str(),c->name,(unsigned long)c->age);
676                         }
677                 }
678                 if (list[strlen(list)-1] != ':')
679                 {
680                         this->WriteLine(list);
681                 }
682         }
683
684         void SendChannelModes(TreeServer* Current)
685         {
686                 char data[MAXBUF];
687                 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
688                 {
689                         SendFJoins(Current, c->second);
690                         snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
691                         this->WriteLine(data);
692                         if (*c->second->topic)
693                         {
694                                 snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",Srv->GetServerName().c_str(),c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
695                                 this->WriteLine(data);
696                         }
697                         for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
698                         {
699                                 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
700                                 this->WriteLine(data);
701                         }
702                         FOREACH_MOD OnSyncChannel(c->second,(Module*)TreeProtocolModule,(void*)this);
703                 }
704         }
705
706         // send all users and their channels
707         void SendUsers(TreeServer* Current)
708         {
709                 char data[MAXBUF];
710                 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
711                 {
712                         if (u->second->registered == 7)
713                         {
714                                 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);
715                                 this->WriteLine(data);
716                                 if (strchr(u->second->modes,'o'))
717                                 {
718                                         this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
719                                 }
720                                 //char* chl = chlist(u->second,u->second);
721                                 //if (*chl)
722                                 //{
723                                 //      this->WriteLine(":"+std::string(u->second->nick)+" FJOIN "+std::string(chl));
724                                 //}
725                                 FOREACH_MOD OnSyncUser(u->second,(Module*)TreeProtocolModule,(void*)this);
726                         }
727                 }
728         }
729
730         void DoBurst(TreeServer* s)
731         {
732                 Srv->SendOpers("*** Bursting to "+s->GetName()+".");
733                 this->WriteLine("BURST");
734                 // Send server tree
735                 this->SendServers(TreeRoot,s,1);
736                 // Send users and their channels
737                 this->SendUsers(s);
738                 // TODO: Send everything else (channel modes etc)
739                 this->SendChannelModes(s);
740                 this->WriteLine("ENDBURST");
741         }
742
743         virtual bool OnDataReady()
744         {
745                 char* data = this->Read();
746                 if (data)
747                 {
748                         this->in_buffer += data;
749                         while (in_buffer.find("\n") != std::string::npos)
750                         {
751                                 char* line = (char*)in_buffer.c_str();
752                                 std::string ret = "";
753                                 while ((*line != '\n') && (strlen(line)))
754                                 {
755                                         ret = ret + *line;
756                                         line++;
757                                 }
758                                 if ((*line == '\n') || (*line == '\r'))
759                                         line++;
760                                 in_buffer = line;
761                                 if (!this->ProcessLine(ret))
762                                 {
763                                         return false;
764                                 }
765                         }
766                 }
767                 return (data != NULL);
768         }
769
770         int WriteLine(std::string line)
771         {
772                 return this->Write(line + "\r\n");
773         }
774
775         bool Error(std::deque<std::string> params)
776         {
777                 if (params.size() < 1)
778                         return false;
779                 std::string Errmsg = params[0];
780                 std::string SName = myhost;
781                 if (InboundServerName != "")
782                 {
783                         SName = InboundServerName;
784                 }
785                 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
786                 // we will return false to cause the socket to close.
787                 return false;
788         }
789
790         bool OperType(std::string prefix, std::deque<std::string> params)
791         {
792                 if (params.size() != 1)
793                         return true;
794                 std::string opertype = params[0];
795                 userrec* u = Srv->FindNick(prefix);
796                 if (u)
797                 {
798                         strlcpy(u->oper,opertype.c_str(),NICKMAX);
799                         if (!strchr(u->modes,'o'))
800                         {
801                                 strcat(u->modes,"o");
802                         }
803                         DoOneToAllButSender(u->server,"OPERTYPE",params,u->server);
804                 }
805                 return true;
806         }
807
808         bool RemoteRehash(std::string prefix, std::deque<std::string> params)
809         {
810                 if (params.size() < 1)
811                         return true;
812                 std::string servermask = params[0];
813                 if (Srv->MatchText(Srv->GetServerName(),servermask))
814                 {
815                         Srv->SendOpers("*** Remote rehash initiated from server \002"+prefix+"\002.");
816                         Srv->RehashServer();
817                         ReadConfiguration(false);
818                 }
819                 DoOneToAllButSender(prefix,"REHASH",params,prefix);
820                 return true;
821         }
822
823         bool RemoteKill(std::string prefix, std::deque<std::string> params)
824         {
825                 if (params.size() != 2)
826                         return true;
827                 std::string nick = params[0];
828                 std::string reason = params[1];
829                 userrec* u = Srv->FindNick(prefix);
830                 userrec* who = Srv->FindNick(nick);
831                 if (who)
832                 {
833                         std::string sourceserv = prefix;
834                         if (u)
835                         {
836                                 sourceserv = u->server;
837                         }
838                         params[1] = ":" + params[1];
839                         DoOneToAllButSender(prefix,"KILL",params,sourceserv);
840                         Srv->QuitUser(who,reason);
841                 }
842                 return true;
843         }
844
845         bool RemoteServer(std::string prefix, std::deque<std::string> params)
846         {
847                 if (params.size() < 4)
848                         return false;
849                 std::string servername = params[0];
850                 std::string password = params[1];
851                 // hopcount is not used for a remote server, we calculate this ourselves
852                 std::string description = params[3];
853                 TreeServer* ParentOfThis = FindServer(prefix);
854                 if (!ParentOfThis)
855                 {
856                         this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
857                         return false;
858                 }
859                 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
860                 ParentOfThis->AddChild(Node);
861                 params[3] = ":" + params[3];
862                 DoOneToAllButSender(prefix,"SERVER",params,prefix);
863                 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
864                 return true;
865         }
866
867         bool Outbound_Reply_Server(std::deque<std::string> params)
868         {
869                 if (params.size() < 4)
870                         return false;
871                 std::string servername = params[0];
872                 std::string password = params[1];
873                 int hops = atoi(params[2].c_str());
874                 if (hops)
875                 {
876                         this->WriteLine("ERROR :Server too far away for authentication");
877                         return false;
878                 }
879                 std::string description = params[3];
880                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
881                 {
882                         if ((x->Name == servername) && (x->RecvPass == password))
883                         {
884                                 // Begin the sync here. this kickstarts the
885                                 // other side, waiting in WAIT_AUTH_2 state,
886                                 // into starting their burst, as it shows
887                                 // that we're happy.
888                                 this->LinkState = CONNECTED;
889                                 // we should add the details of this server now
890                                 // to the servers tree, as a child of the root
891                                 // node.
892                                 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
893                                 TreeRoot->AddChild(Node);
894                                 params[3] = ":" + params[3];
895                                 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
896                                 this->DoBurst(Node);
897                                 return true;
898                         }
899                 }
900                 this->WriteLine("ERROR :Invalid credentials");
901                 return false;
902         }
903
904         bool Inbound_Server(std::deque<std::string> params)
905         {
906                 if (params.size() < 4)
907                         return false;
908                 std::string servername = params[0];
909                 std::string password = params[1];
910                 int hops = atoi(params[2].c_str());
911                 if (hops)
912                 {
913                         this->WriteLine("ERROR :Server too far away for authentication");
914                         return false;
915                 }
916                 std::string description = params[3];
917                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
918                 {
919                         if ((x->Name == servername) && (x->RecvPass == password))
920                         {
921                                 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
922                                 this->InboundServerName = servername;
923                                 this->InboundDescription = description;
924                                 // this is good. Send our details: Our server name and description and hopcount of 0,
925                                 // along with the sendpass from this block.
926                                 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
927                                 // move to the next state, we are now waiting for THEM.
928                                 this->LinkState = WAIT_AUTH_2;
929                                 return true;
930                         }
931                 }
932                 this->WriteLine("ERROR :Invalid credentials");
933                 return false;
934         }
935
936         std::deque<std::string> Split(std::string line, bool stripcolon)
937         {
938                 std::deque<std::string> n;
939                 if (!strchr(line.c_str(),' '))
940                 {
941                         n.push_back(line);
942                         return n;
943                 }
944                 std::stringstream s(line);
945                 std::string param = "";
946                 n.clear();
947                 int item = 0;
948                 while (!s.eof())
949                 {
950                         char c;
951                         s.get(c);
952                         if (c == ' ')
953                         {
954                                 n.push_back(param);
955                                 param = "";
956                                 item++;
957                         }
958                         else
959                         {
960                                 if (!s.eof())
961                                 {
962                                         param = param + c;
963                                 }
964                                 if ((param == ":") && (item > 0))
965                                 {
966                                         param = "";
967                                         while (!s.eof())
968                                         {
969                                                 s.get(c);
970                                                 if (!s.eof())
971                                                 {
972                                                         param = param + c;
973                                                 }
974                                         }
975                                         n.push_back(param);
976                                         param = "";
977                                 }
978                         }
979                 }
980                 if (param != "")
981                 {
982                         n.push_back(param);
983                 }
984                 return n;
985         }
986
987         bool ProcessLine(std::string line)
988         {
989                 char* l = (char*)line.c_str();
990                 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
991                         l[strlen(l)-1] = '\0';
992                 line = l;
993                 if (line == "")
994                         return true;
995                 Srv->Log(DEBUG,"IN: '"+line+"'");
996                 std::deque<std::string> params = this->Split(line,true);
997                 std::string command = "";
998                 std::string prefix = "";
999                 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
1000                 {
1001                         prefix = params[0];
1002                         command = params[1];
1003                         char* pref = (char*)prefix.c_str();
1004                         prefix = ++pref;
1005                         params.pop_front();
1006                         params.pop_front();
1007                 }
1008                 else
1009                 {
1010                         prefix = "";
1011                         command = params[0];
1012                         params.pop_front();
1013                 }
1014                 
1015                 switch (this->LinkState)
1016                 {
1017                         TreeServer* Node;
1018                         
1019                         case WAIT_AUTH_1:
1020                                 // Waiting for SERVER command from remote server. Server initiating
1021                                 // the connection sends the first SERVER command, listening server
1022                                 // replies with theirs if its happy, then if the initiator is happy,
1023                                 // it starts to send its net sync, which starts the merge, otherwise
1024                                 // it sends an ERROR.
1025                                 if (command == "SERVER")
1026                                 {
1027                                         return this->Inbound_Server(params);
1028                                 }
1029                                 else if (command == "ERROR")
1030                                 {
1031                                         return this->Error(params);
1032                                 }
1033                         break;
1034                         case WAIT_AUTH_2:
1035                                 // Waiting for start of other side's netmerge to say they liked our
1036                                 // password.
1037                                 if (command == "SERVER")
1038                                 {
1039                                         // cant do this, they sent it to us in the WAIT_AUTH_1 state!
1040                                         // silently ignore.
1041                                         return true;
1042                                 }
1043                                 else if (command == "BURST")
1044                                 {
1045                                         this->LinkState = CONNECTED;
1046                                         Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
1047                                         TreeRoot->AddChild(Node);
1048                                         params.clear();
1049                                         params.push_back(InboundServerName);
1050                                         params.push_back("*");
1051                                         params.push_back("1");
1052                                         params.push_back(":"+InboundDescription);
1053                                         DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
1054                                         this->DoBurst(Node);
1055                                 }
1056                                 else if (command == "ERROR")
1057                                 {
1058                                         return this->Error(params);
1059                                 }
1060                                 
1061                         break;
1062                         case LISTENER:
1063                                 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
1064                                 return false;
1065                         break;
1066                         case CONNECTING:
1067                                 if (command == "SERVER")
1068                                 {
1069                                         // another server we connected to, which was in WAIT_AUTH_1 state,
1070                                         // has just sent us their credentials. If we get this far, theyre
1071                                         // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
1072                                         // if we're happy with this, we should send our netburst which
1073                                         // kickstarts the merge.
1074                                         return this->Outbound_Reply_Server(params);
1075                                 }
1076                                 else if (command == "ERROR")
1077                                 {
1078                                         return this->Error(params);
1079                                 }
1080                         break;
1081                         case CONNECTED:
1082                                 // This is the 'authenticated' state, when all passwords
1083                                 // have been exchanged and anything past this point is taken
1084                                 // as gospel.
1085                                 std::string target = "";
1086                                 if ((command == "NICK") && (params.size() > 1))
1087                                 {
1088                                         return this->IntroduceClient(prefix,params);
1089                                 }
1090                                 else if (command == "FJOIN")
1091                                 {
1092                                         return this->ForceJoin(prefix,params);
1093                                 }
1094                                 else if (command == "SERVER")
1095                                 {
1096                                         return this->RemoteServer(prefix,params);
1097                                 }
1098                                 else if (command == "ERROR")
1099                                 {
1100                                         return this->Error(params);
1101                                 }
1102                                 else if (command == "OPERTYPE")
1103                                 {
1104                                         return this->OperType(prefix,params);
1105                                 }
1106                                 else if (command == "FMODE")
1107                                 {
1108                                         return this->ForceMode(prefix,params);
1109                                 }
1110                                 else if (command == "KILL")
1111                                 {
1112                                         return this->RemoteKill(prefix,params);
1113                                 }
1114                                 else if (command == "FTOPIC")
1115                                 {
1116                                         return this->ForceTopic(prefix,params);
1117                                 }
1118                                 else if (command == "REHASH")
1119                                 {
1120                                         return this->RemoteRehash(prefix,params);
1121                                 }
1122                                 else if (command == "SQUIT")
1123                                 {
1124                                         if (params.size() == 2)
1125                                         {
1126                                                 this->Squit(FindServer(params[0]),params[1]);
1127                                         }
1128                                         return true;
1129                                 }
1130                                 else
1131                                 {
1132                                         // not a special inter-server command.
1133                                         // Emulate the actual user doing the command,
1134                                         // this saves us having a huge ugly parser.
1135                                         userrec* who = Srv->FindNick(prefix);
1136                                         std::string sourceserv = this->myhost;
1137                                         if (this->InboundServerName != "")
1138                                         {
1139                                                 sourceserv = this->InboundServerName;
1140                                         }
1141                                         if (who)
1142                                         {
1143                                                 // its a user
1144                                                 target = who->server;
1145                                                 char* strparams[127];
1146                                                 for (unsigned int q = 0; q < params.size(); q++)
1147                                                 {
1148                                                         strparams[q] = (char*)params[q].c_str();
1149                                                 }
1150                                                 Srv->CallCommandHandler(command, strparams, params.size(), who);
1151                                         }
1152                                         else
1153                                         {
1154                                                 // its not a user. Its either a server, or somethings screwed up.
1155                                                 if (IsServer(prefix))
1156                                                 {
1157                                                         target = Srv->GetServerName();
1158                                                 }
1159                                                 else
1160                                                 {
1161                                                         log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
1162                                                         return true;
1163                                                 }
1164                                         }
1165                                         return DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
1166
1167                                 }
1168                                 return true;
1169                         break;
1170                 }
1171                 return true;
1172         }
1173
1174         virtual std::string GetName()
1175         {
1176                 std::string sourceserv = this->myhost;
1177                 if (this->InboundServerName != "")
1178                 {
1179                         sourceserv = this->InboundServerName;
1180                 }
1181                 return sourceserv;
1182         }
1183
1184         virtual void OnTimeout()
1185         {
1186                 if (this->LinkState == CONNECTING)
1187                 {
1188                         Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
1189                 }
1190         }
1191
1192         virtual void OnClose()
1193         {
1194                 // Connection closed.
1195                 // If the connection is fully up (state CONNECTED)
1196                 // then propogate a netsplit to all peers.
1197                 std::string quitserver = this->myhost;
1198                 if (this->InboundServerName != "")
1199                 {
1200                         quitserver = this->InboundServerName;
1201                 }
1202                 TreeServer* s = FindServer(quitserver);
1203                 if (s)
1204                 {
1205                         Squit(s,"Remote host closed the connection");
1206                 }
1207         }
1208
1209         virtual int OnIncomingConnection(int newsock, char* ip)
1210         {
1211                 TreeSocket* s = new TreeSocket(newsock, ip);
1212                 Srv->AddSocket(s);
1213                 return true;
1214         }
1215 };
1216
1217 void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
1218 {
1219         for (unsigned int c = 0; c < list.size(); c++)
1220         {
1221                 if (list[c] == server)
1222                 {
1223                         return;
1224                 }
1225         }
1226         list.push_back(server);
1227 }
1228
1229 // returns a list of DIRECT servernames for a specific channel
1230 std::deque<TreeServer*> GetListOfServersForChannel(chanrec* c)
1231 {
1232         std::deque<TreeServer*> list;
1233         std::vector<char*> *ulist = c->GetUsers();
1234         for (unsigned int i = 0; i < ulist->size(); i++)
1235         {
1236                 char* o = (*ulist)[i];
1237                 userrec* otheruser = (userrec*)o;
1238                 if (std::string(otheruser->server) != Srv->GetServerName())
1239                 {
1240                         TreeServer* best = BestRouteTo(otheruser->server);
1241                         if (best)
1242                                 AddThisServer(best,list);
1243                 }
1244         }
1245         return list;
1246 }
1247
1248 bool DoOneToAllButSenderRaw(std::string data,std::string omit,std::string prefix,std::string command,std::deque<std::string> params)
1249 {
1250         TreeServer* omitroute = BestRouteTo(omit);
1251         if ((command == "NOTICE") || (command == "PRIVMSG"))
1252         {
1253                 if (params.size() >= 2)
1254                 {
1255                         if (*(params[0].c_str()) != '#')
1256                         {
1257                                 // special routing for private messages/notices
1258                                 userrec* d = Srv->FindNick(params[0]);
1259                                 if (d)
1260                                 {
1261                                         std::deque<std::string> par;
1262                                         par.clear();
1263                                         par.push_back(params[0]);
1264                                         par.push_back(":"+params[1]);
1265                                         DoOneToOne(prefix,command,par,d->server);
1266                                         return true;
1267                                 }
1268                         }
1269                         else
1270                         {
1271                                 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
1272                                 chanrec* c = Srv->FindChannel(params[0]);
1273                                 if (c)
1274                                 {
1275                                         std::deque<TreeServer*> list = GetListOfServersForChannel(c);
1276                                         log(DEBUG,"Got a list of %d servers",list.size());
1277                                         for (unsigned int i = 0; i < list.size(); i++)
1278                                         {
1279                                                 TreeSocket* Sock = list[i]->GetSocket();
1280                                                 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
1281                                                 {
1282                                                         log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
1283                                                         Sock->WriteLine(data);
1284                                                 }
1285                                         }
1286                                         return true;
1287                                 }
1288                         }
1289                 }
1290         }
1291         for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1292         {
1293                 TreeServer* Route = TreeRoot->GetChild(x);
1294                 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1295                 {
1296                         TreeSocket* Sock = Route->GetSocket();
1297                         Sock->WriteLine(data);
1298                 }
1299         }
1300         return true;
1301 }
1302
1303 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit)
1304 {
1305         TreeServer* omitroute = BestRouteTo(omit);
1306         std::string FullLine = ":" + prefix + " " + command;
1307         for (unsigned int x = 0; x < params.size(); x++)
1308         {
1309                 FullLine = FullLine + " " + params[x];
1310         }
1311         for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1312         {
1313                 TreeServer* Route = TreeRoot->GetChild(x);
1314                 // Send the line IF:
1315                 // The route has a socket (its a direct connection)
1316                 // The route isnt the one to be omitted
1317                 // The route isnt the path to the one to be omitted
1318                 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1319                 {
1320                         TreeSocket* Sock = Route->GetSocket();
1321                         Sock->WriteLine(FullLine);
1322                 }
1323         }
1324         return true;
1325 }
1326
1327 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params)
1328 {
1329         std::string FullLine = ":" + prefix + " " + command;
1330         for (unsigned int x = 0; x < params.size(); x++)
1331         {
1332                 FullLine = FullLine + " " + params[x];
1333         }
1334         for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1335         {
1336                 TreeServer* Route = TreeRoot->GetChild(x);
1337                 if (Route->GetSocket())
1338                 {
1339                         TreeSocket* Sock = Route->GetSocket();
1340                         Sock->WriteLine(FullLine);
1341                 }
1342         }
1343         return true;
1344 }
1345
1346 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target)
1347 {
1348         TreeServer* Route = BestRouteTo(target);
1349         if (Route)
1350         {
1351                 std::string FullLine = ":" + prefix + " " + command;
1352                 for (unsigned int x = 0; x < params.size(); x++)
1353                 {
1354                         FullLine = FullLine + " " + params[x];
1355                 }
1356                 if (Route->GetSocket())
1357                 {
1358                         TreeSocket* Sock = Route->GetSocket();
1359                         Sock->WriteLine(FullLine);
1360                 }
1361                 return true;
1362         }
1363         else
1364         {
1365                 return true;
1366         }
1367 }
1368
1369 std::vector<TreeSocket*> Bindings;
1370
1371 void ReadConfiguration(bool rebind)
1372 {
1373         if (rebind)
1374         {
1375                 for (int j =0; j < Conf->Enumerate("bind"); j++)
1376                 {
1377                         std::string Type = Conf->ReadValue("bind","type",j);
1378                         std::string IP = Conf->ReadValue("bind","address",j);
1379                         long Port = Conf->ReadInteger("bind","port",j,true);
1380                         if (Type == "servers")
1381                         {
1382                                 if (IP == "*")
1383                                 {
1384                                         IP = "";
1385                                 }
1386                                 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
1387                                 if (listener->GetState() == I_LISTENING)
1388                                 {
1389                                         Srv->AddSocket(listener);
1390                                         Bindings.push_back(listener);
1391                                 }
1392                                 else
1393                                 {
1394                                         log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
1395                                         listener->Close();
1396                                         delete listener;
1397                                 }
1398                         }
1399                 }
1400         }
1401         LinkBlocks.clear();
1402         for (int j =0; j < Conf->Enumerate("link"); j++)
1403         {
1404                 Link L;
1405                 L.Name = Conf->ReadValue("link","name",j);
1406                 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
1407                 L.Port = Conf->ReadInteger("link","port",j,true);
1408                 L.SendPass = Conf->ReadValue("link","sendpass",j);
1409                 L.RecvPass = Conf->ReadValue("link","recvpass",j);
1410                 LinkBlocks.push_back(L);
1411                 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
1412         }
1413 }
1414
1415         
1416 class ModuleSpanningTree : public Module
1417 {
1418         std::vector<TreeSocket*> Bindings;
1419         int line;
1420
1421  public:
1422
1423         ModuleSpanningTree()
1424         {
1425                 Srv = new Server;
1426                 Conf = new ConfigReader;
1427                 Bindings.clear();
1428
1429                 // Create the root of the tree
1430                 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
1431
1432                 ReadConfiguration(true);
1433         }
1434
1435         void ShowLinks(TreeServer* Current, userrec* user, int hops)
1436         {
1437                 std::string Parent = TreeRoot->GetName();
1438                 if (Current->GetParent())
1439                 {
1440                         Parent = Current->GetParent()->GetName();
1441                 }
1442                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1443                 {
1444                         ShowLinks(Current->GetChild(q),user,hops+1);
1445                 }
1446                 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
1447         }
1448
1449         void HandleLinks(char** parameters, int pcnt, userrec* user)
1450         {
1451                 ShowLinks(TreeRoot,user,0);
1452                 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
1453                 return;
1454         }
1455
1456         void HandleLusers(char** parameters, int pcnt, userrec* user)
1457         {
1458                 return;
1459         }
1460
1461         // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
1462
1463         void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
1464         {
1465                 if (line < 128)
1466                 {
1467                         for (int t = 0; t < depth; t++)
1468                         {
1469                                 matrix[line][t] = ' ';
1470                         }
1471                         strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
1472                         line++;
1473                         for (unsigned int q = 0; q < Current->ChildCount(); q++)
1474                         {
1475                                 ShowMap(Current->GetChild(q),user,depth+2,matrix);
1476                         }
1477                 }
1478         }
1479
1480         // Ok, prepare to be confused.
1481         // After much mulling over how to approach this, it struck me that
1482         // the 'usual' way of doing a /MAP isnt the best way. Instead of
1483         // keeping track of a ton of ascii characters, and line by line
1484         // under recursion working out where to place them using multiplications
1485         // and divisons, we instead render the map onto a backplane of characters
1486         // (a character matrix), then draw the branches as a series of "L" shapes
1487         // from the nodes. This is not only friendlier on CPU it uses less stack.
1488
1489         void HandleMap(char** parameters, int pcnt, userrec* user)
1490         {
1491                 // This array represents a virtual screen which we will
1492                 // "scratch" draw to, as the console device of an irc
1493                 // client does not provide for a proper terminal.
1494                 char matrix[128][80];
1495                 for (unsigned int t = 0; t < 128; t++)
1496                 {
1497                         matrix[t][0] = '\0';
1498                 }
1499                 line = 0;
1500                 // The only recursive bit is called here.
1501                 ShowMap(TreeRoot,user,0,matrix);
1502                 // Process each line one by one. The algorithm has a limit of
1503                 // 128 servers (which is far more than a spanning tree should have
1504                 // anyway, so we're ok). This limit can be raised simply by making
1505                 // the character matrix deeper, 128 rows taking 10k of memory.
1506                 for (int l = 1; l < line; l++)
1507                 {
1508                         // scan across the line looking for the start of the
1509                         // servername (the recursive part of the algorithm has placed
1510                         // the servers at indented positions depending on what they
1511                         // are related to)
1512                         int first_nonspace = 0;
1513                         while (matrix[l][first_nonspace] == ' ')
1514                         {
1515                                 first_nonspace++;
1516                         }
1517                         first_nonspace--;
1518                         // Draw the `- (corner) section: this may be overwritten by
1519                         // another L shape passing along the same vertical pane, becoming
1520                         // a |- (branch) section instead.
1521                         matrix[l][first_nonspace] = '-';
1522                         matrix[l][first_nonspace-1] = '`';
1523                         int l2 = l - 1;
1524                         // Draw upwards until we hit the parent server, causing possibly
1525                         // other corners (`-) to become branches (|-)
1526                         while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
1527                         {
1528                                 matrix[l2][first_nonspace-1] = '|';
1529                                 l2--;
1530                         }
1531                 }
1532                 // dump the whole lot to the user. This is the easy bit, honest.
1533                 for (int t = 0; t < line; t++)
1534                 {
1535                         WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
1536                 }
1537                 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
1538                 return;
1539         }
1540
1541         int HandleSquit(char** parameters, int pcnt, userrec* user)
1542         {
1543                 return 1;
1544         }
1545
1546         int HandleConnect(char** parameters, int pcnt, userrec* user)
1547         {
1548                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1549                 {
1550                         if (Srv->MatchText(x->Name.c_str(),parameters[0]))
1551                         {
1552                                 WriteServ(user->fd,"NOTICE %s :*** CONNECT: Connecting to server: %s (%s:%d)",user->nick,x->Name.c_str(),x->IPAddr.c_str(),x->Port);
1553                                 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1554                                 Srv->AddSocket(newsocket);
1555                                 return 1;
1556                         }
1557                 }
1558                 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No matching server could be found in the config file.",user->nick);
1559                 return 1;
1560         }
1561
1562         virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
1563         {
1564                 if (command == "CONNECT")
1565                 {
1566                         return this->HandleConnect(parameters,pcnt,user);
1567                 }
1568                 else if (command == "SQUIT")
1569                 {
1570                         return this->HandleSquit(parameters,pcnt,user);
1571                 }
1572                 else if (command == "MAP")
1573                 {
1574                         this->HandleMap(parameters,pcnt,user);
1575                         return 1;
1576                 }
1577                 else if (command == "LUSERS")
1578                 {
1579                         this->HandleLusers(parameters,pcnt,user);
1580                         return 1;
1581                 }
1582                 else if (command == "LINKS")
1583                 {
1584                         this->HandleLinks(parameters,pcnt,user);
1585                         return 1;
1586                 }
1587                 else if (Srv->IsValidModuleCommand(command, pcnt, user))
1588                 {
1589                         // this bit of code cleverly routes all module commands
1590                         // to all remote severs *automatically* so that modules
1591                         // can just handle commands locally, without having
1592                         // to have any special provision in place for remote
1593                         // commands and linking protocols.
1594                         std::deque<std::string> params;
1595                         params.clear();
1596                         for (int j = 0; j < pcnt; j++)
1597                         {
1598                                 if (strchr(parameters[j],' '))
1599                                 {
1600                                         params.push_back(":" + std::string(parameters[j]));
1601                                 }
1602                                 else
1603                                 {
1604                                         params.push_back(std::string(parameters[j]));
1605                                 }
1606                         }
1607                         DoOneToMany(user->nick,command,params);
1608                 }
1609                 return 0;
1610         }
1611
1612         virtual void OnGetServerDescription(std::string servername,std::string &description)
1613         {
1614                 TreeServer* s = FindServer(servername);
1615                 if (s)
1616                 {
1617                         description = s->GetDesc();
1618                 }
1619         }
1620
1621         virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
1622         {
1623                 if (std::string(source->server) == Srv->GetServerName())
1624                 {
1625                         std::deque<std::string> params;
1626                         params.push_back(dest->nick);
1627                         params.push_back(channel->name);
1628                         DoOneToMany(source->nick,"INVITE",params);
1629                 }
1630         }
1631
1632         virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
1633         {
1634                 std::deque<std::string> params;
1635                 params.push_back(chan->name);
1636                 params.push_back(":"+topic);
1637                 DoOneToMany(user->nick,"TOPIC",params);
1638         }
1639
1640         virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
1641         {
1642                 if (target_type == TYPE_USER)
1643                 {
1644                         userrec* d = (userrec*)dest;
1645                         if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1646                         {
1647                                 std::deque<std::string> params;
1648                                 params.clear();
1649                                 params.push_back(d->nick);
1650                                 params.push_back(":"+text);
1651                                 DoOneToOne(user->nick,"NOTICE",params,d->server);
1652                         }
1653                 }
1654                 else
1655                 {
1656                         if (std::string(user->server) == Srv->GetServerName())
1657                         {
1658                                 chanrec *c = (chanrec*)dest;
1659                                 std::deque<TreeServer*> list = GetListOfServersForChannel(c);
1660                                 for (unsigned int i = 0; i < list.size(); i++)
1661                                 {
1662                                         TreeSocket* Sock = list[i]->GetSocket();
1663                                         if (Sock)
1664                                                 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+std::string(c->name)+" :"+text);
1665                                 }
1666                         }
1667                 }
1668         }
1669
1670         virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
1671         {
1672                 if (target_type == TYPE_USER)
1673                 {
1674                         // route private messages which are targetted at clients only to the server
1675                         // which needs to receive them
1676                         userrec* d = (userrec*)dest;
1677                         if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1678                         {
1679                                 std::deque<std::string> params;
1680                                 params.clear();
1681                                 params.push_back(d->nick);
1682                                 params.push_back(":"+text);
1683                                 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
1684                         }
1685                 }
1686                 else
1687                 {
1688                         if (std::string(user->server) == Srv->GetServerName())
1689                         {
1690                                 chanrec *c = (chanrec*)dest;
1691                                 std::deque<TreeServer*> list = GetListOfServersForChannel(c);
1692                                 for (unsigned int i = 0; i < list.size(); i++)
1693                                 {
1694                                         TreeSocket* Sock = list[i]->GetSocket();
1695                                         if (Sock)
1696                                                 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+std::string(c->name)+" :"+text);
1697                                 }
1698                         }
1699                 }
1700         }
1701
1702         virtual void OnUserJoin(userrec* user, chanrec* channel)
1703         {
1704                 // Only do this for local users
1705                 if (std::string(user->server) == Srv->GetServerName())
1706                 {
1707                         std::deque<std::string> params;
1708                         params.clear();
1709                         params.push_back(channel->name);
1710                         if (*channel->key)
1711                         {
1712                                 // if the channel has a key, force the join by emulating the key.
1713                                 params.push_back(channel->key);
1714                         }
1715                         DoOneToMany(user->nick,"JOIN",params);
1716                 }
1717         }
1718
1719         virtual void OnUserPart(userrec* user, chanrec* channel)
1720         {
1721                 if (std::string(user->server) == Srv->GetServerName())
1722                 {
1723                         std::deque<std::string> params;
1724                         params.clear();
1725                         params.push_back(channel->name);
1726                         DoOneToMany(user->nick,"PART",params);
1727                 }
1728         }
1729
1730         virtual void OnUserConnect(userrec* user)
1731         {
1732                 char agestr[MAXBUF];
1733                 if (std::string(user->server) == Srv->GetServerName())
1734                 {
1735                         std::deque<std::string> params;
1736                         snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
1737                         params.clear();
1738                         params.push_back(agestr);
1739                         params.push_back(user->nick);
1740                         params.push_back(user->host);
1741                         params.push_back(user->dhost);
1742                         params.push_back(user->ident);
1743                         params.push_back("+"+std::string(user->modes));
1744                         params.push_back(user->ip);
1745                         params.push_back(":"+std::string(user->fullname));
1746                         DoOneToMany(Srv->GetServerName(),"NICK",params);
1747                 }
1748         }
1749
1750         virtual void OnUserQuit(userrec* user, std::string reason)
1751         {
1752                 if (std::string(user->server) == Srv->GetServerName())
1753                 {
1754                         std::deque<std::string> params;
1755                         params.push_back(":"+reason);
1756                         DoOneToMany(user->nick,"QUIT",params);
1757                 }
1758         }
1759
1760         virtual void OnUserPostNick(userrec* user, std::string oldnick)
1761         {
1762                 if (std::string(user->server) == Srv->GetServerName())
1763                 {
1764                         std::deque<std::string> params;
1765                         params.push_back(user->nick);
1766                         DoOneToMany(oldnick,"NICK",params);
1767                 }
1768         }
1769
1770         virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
1771         {
1772                 if (std::string(source->server) == Srv->GetServerName())
1773                 {
1774                         std::deque<std::string> params;
1775                         params.push_back(chan->name);
1776                         params.push_back(user->nick);
1777                         params.push_back(":"+reason);
1778                         DoOneToMany(source->nick,"KICK",params);
1779                 }
1780         }
1781
1782         virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
1783         {
1784                 std::deque<std::string> params;
1785                 params.push_back(dest->nick);
1786                 params.push_back(":"+reason);
1787                 DoOneToMany(source->nick,"KILL",params);
1788         }
1789
1790         virtual void OnRehash(std::string parameter)
1791         {
1792                 if (parameter != "")
1793                 {
1794                         std::deque<std::string> params;
1795                         params.push_back(parameter);
1796                         DoOneToMany(Srv->GetServerName(),"REHASH",params);
1797                         // check for self
1798                         if (Srv->MatchText(Srv->GetServerName(),parameter))
1799                         {
1800                                 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
1801                                 Srv->RehashServer();
1802                         }
1803                 }
1804                 ReadConfiguration(false);
1805         }
1806
1807         // note: the protocol does not allow direct umode +o except
1808         // via NICK with 8 params. sending OPERTYPE infers +o modechange
1809         // locally.
1810         virtual void OnOper(userrec* user, std::string opertype)
1811         {
1812                 if (std::string(user->server) == Srv->GetServerName())
1813                 {
1814                         std::deque<std::string> params;
1815                         params.push_back(opertype);
1816                         DoOneToMany(user->nick,"OPERTYPE",params);
1817                 }
1818         }
1819
1820         virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
1821         {
1822                 if (std::string(user->server) == Srv->GetServerName())
1823                 {
1824                         if (target_type == TYPE_USER)
1825                         {
1826                                 userrec* u = (userrec*)dest;
1827                                 std::deque<std::string> params;
1828                                 params.push_back(u->nick);
1829                                 params.push_back(text);
1830                                 DoOneToMany(user->nick,"MODE",params);
1831                         }
1832                         else
1833                         {
1834                                 chanrec* c = (chanrec*)dest;
1835                                 std::deque<std::string> params;
1836                                 params.push_back(c->name);
1837                                 params.push_back(text);
1838                                 DoOneToMany(user->nick,"MODE",params);
1839                         }
1840                 }
1841         }
1842
1843         virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
1844         {
1845                 TreeSocket* s = (TreeSocket*)opaque;
1846                 if (target)
1847                 {
1848                         if (target_type == TYPE_USER)
1849                         {
1850                                 userrec* u = (userrec*)target;
1851                                 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
1852                         }
1853                         else
1854                         {
1855                                 chanrec* c = (chanrec*)target;
1856                                 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
1857                         }
1858                 }
1859         }
1860
1861         virtual ~ModuleSpanningTree()
1862         {
1863                 delete Srv;
1864         }
1865
1866         virtual Version GetVersion()
1867         {
1868                 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
1869         }
1870 };
1871
1872
1873 class ModuleSpanningTreeFactory : public ModuleFactory
1874 {
1875  public:
1876         ModuleSpanningTreeFactory()
1877         {
1878         }
1879         
1880         ~ModuleSpanningTreeFactory()
1881         {
1882         }
1883         
1884         virtual Module * CreateModule()
1885         {
1886                 TreeProtocolModule = new ModuleSpanningTree;
1887                 return TreeProtocolModule;
1888         }
1889         
1890 };
1891
1892
1893 extern "C" void * init_module( void )
1894 {
1895         return new ModuleSpanningTreeFactory;
1896 }
1897