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