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