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