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