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