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