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