]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree.cpp
d63c11cbf0c4a84a9001b6b2007829fdb2337660
[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 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
46
47 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
48 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;
49
50 extern user_hash clientlist;
51 extern chan_hash chanlist;
52
53 class TreeServer;
54 class TreeSocket;
55
56 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target);
57 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit);
58 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params);
59 bool DoOneToAllButSenderRaw(std::string data,std::string omit);
60
61 class TreeServer
62 {
63         TreeServer* Parent;
64         std::vector<TreeServer*> Children;
65         std::string ServerName;
66         std::string ServerDesc;
67         std::string VersionString;
68         int UserCount;
69         int OperCount;
70         TreeSocket* Socket;     // for directly connected servers this points at the socket object
71         
72  public:
73
74         TreeServer()
75         {
76                 Parent = NULL;
77                 ServerName = "";
78                 ServerDesc = "";
79                 VersionString = "";
80                 UserCount = OperCount = 0;
81         }
82
83         TreeServer(std::string Name, std::string Desc) : ServerName(Name), ServerDesc(Desc)
84         {
85                 Parent = NULL;
86                 VersionString = "";
87                 UserCount = OperCount = 0;
88         }
89
90         TreeServer(std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock) : Parent(Above), ServerName(Name), ServerDesc(Desc), Socket(Sock)
91         {
92                 VersionString = "";
93                 UserCount = OperCount = 0;
94         }
95
96         std::string GetName()
97         {
98                 return this->ServerName;
99         }
100
101         std::string GetDesc()
102         {
103                 return this->ServerDesc;
104         }
105
106         std::string GetVersion()
107         {
108                 return this->VersionString;
109         }
110
111         int GetUserCount()
112         {
113                 return this->UserCount;
114         }
115
116         int GetOperCount()
117         {
118                 return this->OperCount;
119         }
120
121         TreeSocket* GetSocket()
122         {
123                 return this->Socket;
124         }
125
126         TreeServer* GetParent()
127         {
128                 return this->Parent;
129         }
130
131         unsigned int ChildCount()
132         {
133                 return Children.size();
134         }
135
136         TreeServer* GetChild(unsigned int n)
137         {
138                 if (n < Children.size())
139                 {
140                         return Children[n];
141                 }
142                 else
143                 {
144                         return NULL;
145                 }
146         }
147
148         void AddChild(TreeServer* Child)
149         {
150                 Children.push_back(Child);
151         }
152
153         bool DelChild(TreeServer* Child)
154         {
155                 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
156                 {
157                         if (*a == Child)
158                         {
159                                 Children.erase(a);
160                                 return true;
161                         }
162                 }
163                 return false;
164         }
165
166         // removes child nodes of this node, and of that node, etc etc
167         bool Tidy()
168         {
169                 bool stillchildren = true;
170                 while (stillchildren)
171                 {
172                         stillchildren = false;
173                         for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
174                         {
175                                 TreeServer* s = (TreeServer*)*a;
176                                 s->Tidy();
177                                 Children.erase(a);
178                                 delete s;
179                                 stillchildren = true;
180                                 break;
181                         }
182                 }
183                 return true;
184         }
185 };
186
187 class Link
188 {
189  public:
190          std::string Name;
191          std::string IPAddr;
192          int Port;
193          std::string SendPass;
194          std::string RecvPass;
195 };
196
197 /* $ModDesc: Povides a spanning tree server link protocol */
198
199 Server *Srv;
200 ConfigReader *Conf;
201 TreeServer *TreeRoot;
202 std::vector<Link> LinkBlocks;
203
204 TreeServer* RouteEnumerate(TreeServer* Current, std::string ServerName)
205 {
206         if (Current->GetName() == ServerName)
207                 return Current;
208         for (unsigned int q = 0; q < Current->ChildCount(); q++)
209         {
210                 TreeServer* found = RouteEnumerate(Current->GetChild(q),ServerName);
211                 if (found)
212                 {
213                         return found;
214                 }
215         }
216         return NULL;
217 }
218
219 // Returns the locally connected server we must route a
220 // message through to reach server 'ServerName'. This
221 // only applies to one-to-one and not one-to-many routing.
222 TreeServer* BestRouteTo(std::string ServerName)
223 {
224         log(DEBUG,"Finding best route to %s",ServerName.c_str());
225         // first, find the server by recursively walking the tree
226         TreeServer* Found = RouteEnumerate(TreeRoot,ServerName);
227         // did we find it? If not, they did something wrong, abort.
228         if (!Found)
229         {
230                 log(DEBUG,"Failed to find %s by walking tree!",ServerName.c_str());
231                 return NULL;
232         }
233         else
234         {
235                 // The server exists, follow its parent nodes until
236                 // the parent of the current is 'TreeRoot', we know
237                 // then that this is a directly-connected server.
238                 while ((Found) && (Found->GetParent() != TreeRoot))
239                 {
240                         Found = Found->GetParent();
241                 }
242                 log(DEBUG,"Route to %s is via %s",ServerName.c_str(),Found->GetName().c_str());
243                 return Found;
244         }
245 }
246
247 bool LookForServer(TreeServer* Current, std::string ServerName)
248 {
249         if (ServerName == Current->GetName())
250                 return true;
251         for (unsigned int q = 0; q < Current->ChildCount(); q++)
252         {
253                 if (LookForServer(Current->GetChild(q),ServerName))
254                         return true;
255         }
256         return false;
257 }
258
259 TreeServer* Found;
260
261 void RFindServer(TreeServer* Current, std::string ServerName)
262 {
263         if ((ServerName == Current->GetName()) && (!Found))
264         {
265                 Found = Current;
266                 log(DEBUG,"Found server %s desc %s",Current->GetName().c_str(),Current->GetDesc().c_str());
267                 return;
268         }
269         if (!Found)
270         {
271                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
272                 {
273                         if (!Found)
274                                 RFindServer(Current->GetChild(q),ServerName);
275                 }
276         }
277         return;
278 }
279
280 TreeServer* FindServer(std::string ServerName)
281 {
282         Found = NULL;
283         RFindServer(TreeRoot,ServerName);
284         return Found;
285 }
286
287 bool IsServer(std::string ServerName)
288 {
289         return LookForServer(TreeRoot,ServerName);
290 }
291
292 class TreeSocket : public InspSocket
293 {
294         std::string myhost;
295         std::string in_buffer;
296         ServerState LinkState;
297         std::string InboundServerName;
298         std::string InboundDescription;
299         int num_lost_users;
300         int num_lost_servers;
301         
302  public:
303
304         TreeSocket(std::string host, int port, bool listening, unsigned long maxtime)
305                 : InspSocket(host, port, listening, maxtime)
306         {
307                 Srv->Log(DEBUG,"Create new listening");
308                 myhost = host;
309                 this->LinkState = LISTENER;
310         }
311
312         TreeSocket(std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
313                 : InspSocket(host, port, listening, maxtime)
314         {
315                 Srv->Log(DEBUG,"Create new outbound");
316                 myhost = ServerName;
317                 this->LinkState = CONNECTING;
318         }
319
320         TreeSocket(int newfd, char* ip)
321                 : InspSocket(newfd, ip)
322         {
323                 Srv->Log(DEBUG,"Associate new inbound");
324                 this->LinkState = WAIT_AUTH_1;
325         }
326         
327         virtual bool OnConnected()
328         {
329                 if (this->LinkState == CONNECTING)
330                 {
331                         Srv->SendOpers("*** Connection to "+myhost+"["+this->GetIP()+"] established.");
332                         // we should send our details here.
333                         // if the other side is satisfied, they send theirs.
334                         // we do not need to change state here.
335                         for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
336                         {
337                                 if (x->Name == this->myhost)
338                                 {
339                                         // found who we're supposed to be connecting to, send the neccessary gubbins.
340                                         this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
341                                         return true;
342                                 }
343                         }
344                 }
345                 log(DEBUG,"Outbound connection ERROR: Could not find the right link block!");
346                 return true;
347         }
348         
349         virtual void OnError(InspSocketError e)
350         {
351         }
352
353         virtual int OnDisconnect()
354         {
355                 return true;
356         }
357
358         // recursively send the server tree with distances as hops
359         void SendServers(TreeServer* Current, TreeServer* s, int hops)
360         {
361                 char command[1024];
362                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
363                 {
364                         TreeServer* recursive_server = Current->GetChild(q);
365                         if (recursive_server != s)
366                         {
367                                 // :source.server SERVER server.name hops :Description
368                                 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
369                                 this->WriteLine(command);
370                                 // down to next level
371                                 this->SendServers(recursive_server, s, hops+1);
372                         }
373                 }
374         }
375
376         void SquitServer(TreeServer* Current)
377         {
378                 // recursively squit the servers attached to 'Current'
379                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
380                 {
381                         TreeServer* recursive_server = Current->GetChild(q);
382                         this->SquitServer(recursive_server);
383                 }
384                 // Now we've whacked the kids, whack self
385                 log(DEBUG,"Deleted %s",Current->GetName().c_str());
386                 num_lost_servers++;
387                 bool quittingpeople = true;
388                 while (quittingpeople)
389                 {
390                         quittingpeople = false;
391                         for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
392                         {
393                                 if (!strcasecmp(u->second->server,Current->GetName().c_str()))
394                                 {
395                                         log(DEBUG,"Quitting user %s of server %s",u->second->nick,u->second->server);
396                                         Srv->QuitUser(u->second,Current->GetName()+" "+std::string(Srv->GetServerName()));
397                                         num_lost_users++;
398                                         quittingpeople = true;
399                                         break;
400                                 }
401                         }
402                 }
403         }
404
405         void Squit(TreeServer* Current,std::string reason)
406         {
407                 if (Current)
408                 {
409                         std::deque<std::string> params;
410                         params.push_back(Current->GetName());
411                         params.push_back(":"+reason);
412                         DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
413                         if (Current->GetParent() == TreeRoot)
414                         {
415                                 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
416                         }
417                         else
418                         {
419                                 Srv->SendOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
420                         }
421                         num_lost_servers = 0;
422                         num_lost_users = 0;
423                         SquitServer(Current);
424                         Current->Tidy();
425                         Current->GetParent()->DelChild(Current);
426                         delete Current;
427                         WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
428                 }
429                 else
430                 {
431                         log(DEBUG,"Squit from unknown server");
432                 }
433         }
434
435         bool ForceMode(std::string source, std::deque<std::string> params)
436         {
437                 userrec* who = new userrec;
438                 who->fd = FD_MAGIC_NUMBER;
439                 if (params.size() < 2)
440                         return true;
441                 char* modelist[255];
442                 for (unsigned int q = 0; q < params.size(); q++)
443                 {
444                         modelist[q] = (char*)params[q].c_str();
445                 }
446                 Srv->SendMode(modelist,params.size(),who);
447                 DoOneToAllButSender(source,"FMODE",params,source);
448                 delete who;
449                 return true;
450         }
451
452         bool ForceJoin(std::string source, std::deque<std::string> params)
453         {
454                 if (params.size() < 1)
455                         return true;
456                 for (unsigned int channelnum = 0; channelnum < params.size(); channelnum++)
457                 {
458                         // process one channel at a time, applying modes.
459                         char* channel = (char*)params[channelnum].c_str();
460                         char permissions = *channel;
461                         char* mode = NULL;
462                         switch (permissions)
463                         {
464                                 case '@':
465                                         channel++;
466                                         mode = "+o";
467                                 break;
468                                 case '%':
469                                         channel++;
470                                         mode = "+h";
471                                 break;
472                                 case '+':
473                                         channel++;
474                                         mode = "+v";
475                                 break;
476                         }
477                         userrec* who = Srv->FindNick(source);
478                         if (who)
479                         {
480                                 char* key = "";
481                                 chanrec* chan = Srv->FindChannel(channel);
482                                 if ((chan) && (*chan->key))
483                                 {
484                                         key = chan->key;
485                                 }
486                                 Srv->JoinUserToChannel(who,channel,key);
487                                 if (mode)
488                                 {
489                                         char* modelist[3];
490                                         modelist[0] = channel;
491                                         modelist[1] = mode;
492                                         modelist[2] = who->nick;
493                                         Srv->SendMode(modelist,3,who);
494                                 }
495                                 DoOneToAllButSender(source,"FJOIN",params,who->server);
496                         }
497                 }
498                 return true;
499         }
500
501         bool IntroduceClient(std::string source, std::deque<std::string> params)
502         {
503                 if (params.size() < 8)
504                         return true;
505                 // NICK age nick host dhost ident +modes ip :gecos
506                 //       0   1    2    3      4     5    6   7
507                 std::string nick = params[1];
508                 std::string host = params[2];
509                 std::string dhost = params[3];
510                 std::string ident = params[4];
511                 time_t age = atoi(params[0].c_str());
512                 std::string modes = params[5];
513                 if (*(modes.c_str()) == '+')
514                 {
515                         char* m = (char*)modes.c_str();
516                         m++;
517                         modes = m;
518                 }
519                 std::string ip = params[6];
520                 std::string gecos = params[7];
521                 char* tempnick = (char*)nick.c_str();
522                 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
523                 
524                 user_hash::iterator iter;
525                 iter = clientlist.find(tempnick);
526                 if (iter != clientlist.end())
527                 {
528                         // nick collision
529                         log(DEBUG,"Nick collision on %s!%s@%s",tempnick,ident.c_str(),host.c_str());
530                         return true;
531                 }
532                 
533                 clientlist[tempnick] = new userrec();
534                 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
535                 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
536                 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
537                 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
538                 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
539                 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
540                 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
541                 clientlist[tempnick]->registered = 7;
542                 clientlist[tempnick]->signon = age;
543                 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
544                 for (int i = 0; i < MAXCHANS; i++)
545                 {
546                         clientlist[tempnick]->chans[i].channel = NULL;
547                         clientlist[tempnick]->chans[i].uc_modes = 0;
548                 }
549                 DoOneToAllButSender(source,"NICK",params,source);
550                 return true;
551         }
552
553         void SendChannelModes(TreeServer* Current)
554         {
555                 char data[MAXBUF];
556                 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
557                 {
558                         snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
559                         this->WriteLine(data);
560                         if (*c->second->topic)
561                         {
562                                 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);
563                                 this->WriteLine(data);
564                         }
565                         for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
566                         {
567                                 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
568                                 this->WriteLine(data);
569                         }
570                 }
571         }
572
573         // send all users and their channels
574         void SendUsers(TreeServer* Current)
575         {
576                 char data[MAXBUF];
577                 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
578                 {
579                         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);
580                         this->WriteLine(data);
581                         if (strchr(u->second->modes,'o'))
582                         {
583                                 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
584                         }
585                         char* chl = chlist(u->second,u->second);
586                         if (*chl)
587                         {
588                                 this->WriteLine(":"+std::string(u->second->nick)+" FJOIN "+std::string(chl));
589                         }
590                 }
591         }
592
593         void DoBurst(TreeServer* s)
594         {
595                 log(DEBUG,"Beginning network burst");
596                 Srv->SendOpers("*** Bursting to "+s->GetName()+".");
597                 this->WriteLine("BURST");
598                 // Send server tree
599                 this->SendServers(TreeRoot,s,1);
600                 // Send users and their channels
601                 this->SendUsers(s);
602                 // TODO: Send everything else (channel modes etc)
603                 this->SendChannelModes(s);
604                 this->WriteLine("ENDBURST");
605         }
606
607         virtual bool OnDataReady()
608         {
609                 char* data = this->Read();
610                 if (data)
611                 {
612                         this->in_buffer += data;
613                         while (in_buffer.find("\n") != std::string::npos)
614                         {
615                                 char* line = (char*)in_buffer.c_str();
616                                 std::string ret = "";
617                                 while ((*line != '\n') && (strlen(line)))
618                                 {
619                                         ret = ret + *line;
620                                         line++;
621                                 }
622                                 if ((*line == '\n') || (*line == '\r'))
623                                         line++;
624                                 in_buffer = line;
625                                 if (!this->ProcessLine(ret))
626                                 {
627                                         return false;
628                                 }
629                         }
630                 }
631                 return (data != NULL);
632         }
633
634         int WriteLine(std::string line)
635         {
636                 return this->Write(line + "\r\n");
637         }
638
639         bool Error(std::deque<std::string> params)
640         {
641                 if (params.size() < 1)
642                         return false;
643                 std::string Errmsg = params[0];
644                 std::string SName = myhost;
645                 if (InboundServerName != "")
646                 {
647                         SName = InboundServerName;
648                 }
649                 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
650                 // we will return false to cause the socket to close.
651                 return false;
652         }
653
654         bool OperType(std::string prefix, std::deque<std::string> params)
655         {
656                 if (params.size() != 1)
657                         return true;
658                 std::string opertype = params[0];
659                 userrec* u = Srv->FindNick(prefix);
660                 if (u)
661                 {
662                         strlcpy(u->oper,opertype.c_str(),NICKMAX);
663                         if (!strchr(u->modes,'o'))
664                         {
665                                 strcat(u->modes,"o");
666                         }
667                         DoOneToAllButSender(u->server,"OPERTYPE",params,u->server);
668                 }
669                 return true;
670         }
671
672         bool RemoteServer(std::string prefix, std::deque<std::string> params)
673         {
674                 if (params.size() < 4)
675                         return false;
676                 std::string servername = params[0];
677                 std::string password = params[1];
678                 int hops = atoi(params[2].c_str());
679                 std::string description = params[3];
680                 if (!hops)
681                 {
682                         this->WriteLine("ERROR :Protocol error - Introduced remote server with incorrect hopcount!");
683                         return false;
684                 }
685                 TreeServer* ParentOfThis = FindServer(prefix);
686                 if (!ParentOfThis)
687                 {
688                         this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
689                         return false;
690                 }
691                 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
692                 ParentOfThis->AddChild(Node);
693                 params[3] = ":" + params[3];
694                 DoOneToAllButSender(prefix,"SERVER",params,prefix);
695                 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
696                 return true;
697         }
698
699         bool Outbound_Reply_Server(std::deque<std::string> params)
700         {
701                 if (params.size() < 4)
702                         return false;
703                 std::string servername = params[0];
704                 std::string password = params[1];
705                 int hops = atoi(params[2].c_str());
706                 if (hops)
707                 {
708                         this->WriteLine("ERROR :Server too far away for authentication");
709                         return false;
710                 }
711                 std::string description = params[3];
712                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
713                 {
714                         if ((x->Name == servername) && (x->RecvPass == password))
715                         {
716                                 // Begin the sync here. this kickstarts the
717                                 // other side, waiting in WAIT_AUTH_2 state,
718                                 // into starting their burst, as it shows
719                                 // that we're happy.
720                                 this->LinkState = CONNECTED;
721                                 // we should add the details of this server now
722                                 // to the servers tree, as a child of the root
723                                 // node.
724                                 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
725                                 TreeRoot->AddChild(Node);
726                                 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
727                                 this->DoBurst(Node);
728                                 return true;
729                         }
730                 }
731                 this->WriteLine("ERROR :Invalid credentials");
732                 return false;
733         }
734
735         bool Inbound_Server(std::deque<std::string> params)
736         {
737                 if (params.size() < 4)
738                         return false;
739                 std::string servername = params[0];
740                 std::string password = params[1];
741                 int hops = atoi(params[2].c_str());
742                 if (hops)
743                 {
744                         this->WriteLine("ERROR :Server too far away for authentication");
745                         return false;
746                 }
747                 std::string description = params[3];
748                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
749                 {
750                         if ((x->Name == servername) && (x->RecvPass == password))
751                         {
752                                 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
753                                 this->InboundServerName = servername;
754                                 this->InboundDescription = description;
755                                 // this is good. Send our details: Our server name and description and hopcount of 0,
756                                 // along with the sendpass from this block.
757                                 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
758                                 // move to the next state, we are now waiting for THEM.
759                                 this->LinkState = WAIT_AUTH_2;
760                                 return true;
761                         }
762                 }
763                 this->WriteLine("ERROR :Invalid credentials");
764                 return false;
765         }
766
767         std::deque<std::string> Split(std::string line, bool stripcolon)
768         {
769                 std::deque<std::string> n;
770                 std::stringstream s(line);
771                 std::string param = "";
772                 n.clear();
773                 int item = 0;
774                 while (!s.eof())
775                 {
776                         s >> param;
777                         if ((param != "") && (param != "\n"))
778                         {
779                                 if ((param.c_str()[0] == ':') && (item))
780                                 {
781                                         char* str = (char*)param.c_str();
782                                         str++;
783                                         param = str;
784                                         std::string append;
785                                         while (!s.eof())
786                                         {
787                                                 append = "";
788                                                 s >> append;
789                                                 if (append != "")
790                                                 {
791                                                         param = param + " " + append;
792                                                 }
793                                         }
794                                 }
795                                 item++;
796                                 n.push_back(param);
797                         }
798                 }
799                 return n;
800         }
801
802         bool ProcessLine(std::string line)
803         {
804                 char* l = (char*)line.c_str();
805                 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
806                         l[strlen(l)-1] = '\0';
807                 line = l;
808                 if (line == "")
809                         return true;
810                 Srv->Log(DEBUG,"inbound-line: '"+line+"'");
811                 std::deque<std::string> params = this->Split(line,true);
812                 std::string command = "";
813                 std::string prefix = "";
814                 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
815                 {
816                         prefix = params[0];
817                         command = params[1];
818                         char* pref = (char*)prefix.c_str();
819                         prefix = ++pref;
820                         params.pop_front();
821                         params.pop_front();
822                 }
823                 else
824                 {
825                         prefix = "";
826                         command = params[0];
827                         params.pop_front();
828                 }
829                 
830                 switch (this->LinkState)
831                 {
832                         TreeServer* Node;
833                         
834                         case WAIT_AUTH_1:
835                                 // Waiting for SERVER command from remote server. Server initiating
836                                 // the connection sends the first SERVER command, listening server
837                                 // replies with theirs if its happy, then if the initiator is happy,
838                                 // it starts to send its net sync, which starts the merge, otherwise
839                                 // it sends an ERROR.
840                                 if (command == "SERVER")
841                                 {
842                                         return this->Inbound_Server(params);
843                                 }
844                                 else if (command == "ERROR")
845                                 {
846                                         return this->Error(params);
847                                 }
848                         break;
849                         case WAIT_AUTH_2:
850                                 // Waiting for start of other side's netmerge to say they liked our
851                                 // password.
852                                 if (command == "SERVER")
853                                 {
854                                         // cant do this, they sent it to us in the WAIT_AUTH_1 state!
855                                         // silently ignore.
856                                         return true;
857                                 }
858                                 else if (command == "BURST")
859                                 {
860                                         this->LinkState = CONNECTED;
861                                         Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
862                                         TreeRoot->AddChild(Node);
863                                         params.clear();
864                                         params.push_back(InboundServerName);
865                                         params.push_back("*");
866                                         params.push_back("1");
867                                         params.push_back(":"+InboundDescription);
868                                         DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
869                                         this->DoBurst(Node);
870                                 }
871                                 else if (command == "ERROR")
872                                 {
873                                         return this->Error(params);
874                                 }
875                                 
876                         break;
877                         case LISTENER:
878                                 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
879                                 return false;
880                         break;
881                         case CONNECTING:
882                                 if (command == "SERVER")
883                                 {
884                                         // another server we connected to, which was in WAIT_AUTH_1 state,
885                                         // has just sent us their credentials. If we get this far, theyre
886                                         // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
887                                         // if we're happy with this, we should send our netburst which
888                                         // kickstarts the merge.
889                                         return this->Outbound_Reply_Server(params);
890                                 }
891                         break;
892                         case CONNECTED:
893                                 // This is the 'authenticated' state, when all passwords
894                                 // have been exchanged and anything past this point is taken
895                                 // as gospel.
896                                 std::string target = "";
897                                 if ((command == "NICK") && (params.size() > 1))
898                                 {
899                                         return this->IntroduceClient(prefix,params);
900                                 }
901                                 else if (command == "FJOIN")
902                                 {
903                                         return this->ForceJoin(prefix,params);
904                                 }
905                                 else if (command == "SERVER")
906                                 {
907                                         return this->RemoteServer(prefix,params);
908                                 }
909                                 else if (command == "OPERTYPE")
910                                 {
911                                         return this->OperType(prefix,params);
912                                 }
913                                 else if (command == "FMODE")
914                                 {
915                                         return this->ForceMode(prefix,params);
916                                 }
917                                 else if (command == "SQUIT")
918                                 {
919                                         if (params.size() == 2)
920                                         {
921                                                 this->Squit(FindServer(params[0]),params[1]);
922                                         }
923                                         return true;
924                                 }
925                                 else
926                                 {
927                                         // not a special inter-server command.
928                                         // Emulate the actual user doing the command,
929                                         // this saves us having a huge ugly parser.
930                                         userrec* who = Srv->FindNick(prefix);
931                                         std::string sourceserv = this->myhost;
932                                         if (this->InboundServerName != "")
933                                         {
934                                                 sourceserv = this->InboundServerName;
935                                         }
936                                         if (who)
937                                         {
938                                                 // its a user
939                                                 target = who->server;
940                                                 char* strparams[127];
941                                                 for (unsigned int q = 0; q < params.size(); q++)
942                                                 {
943                                                         strparams[q] = (char*)params[q].c_str();
944                                                 }
945                                                 log(DEBUG,"*** CALL COMMAND HANDLER FOR %s, SOURCE: '%s'",command.c_str(),who->nick);
946                                                 Srv->CallCommandHandler(command, strparams, params.size(), who);
947                                         }
948                                         else
949                                         {
950                                                 // its not a user. Its either a server, or somethings screwed up.
951                                                 if (IsServer(prefix))
952                                                 {
953                                                         target = Srv->GetServerName();
954                                                 }
955                                                 else
956                                                 {
957                                                         log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
958                                                         return true;
959                                                 }
960                                         }
961                                         return DoOneToAllButSenderRaw(line,sourceserv);
962
963                                 }
964                                 return true;
965                         break;  
966                 }
967                 return true;
968         }
969
970         virtual void OnTimeout()
971         {
972                 if (this->LinkState == CONNECTING)
973                 {
974                         Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
975                 }
976         }
977
978         virtual void OnClose()
979         {
980                 // Connection closed.
981                 // If the connection is fully up (state CONNECTED)
982                 // then propogate a netsplit to all peers.
983                 std::string quitserver = this->myhost;
984                 if (this->InboundServerName != "")
985                 {
986                         quitserver = this->InboundServerName;
987                 }
988                 TreeServer* s = FindServer(quitserver);
989                 if (s)
990                 {
991                         Squit(s,"Remote host closed the connection");
992                 }
993         }
994
995         virtual int OnIncomingConnection(int newsock, char* ip)
996         {
997                 TreeSocket* s = new TreeSocket(newsock, ip);
998                 Srv->AddSocket(s);
999                 return true;
1000         }
1001 };
1002
1003 bool DoOneToAllButSenderRaw(std::string data,std::string omit)
1004 {
1005         for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1006         {
1007                 TreeServer* Route = TreeRoot->GetChild(x);
1008                 if ((Route->GetSocket()) && (Route->GetName() != omit) && (BestRouteTo(omit) != Route))
1009                 {
1010                         TreeSocket* Sock = Route->GetSocket();
1011                         log(DEBUG,"Sending RAW to %s",Route->GetName().c_str());
1012                         Sock->WriteLine(data);
1013                 }
1014         }
1015         return true;
1016 }
1017
1018 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit)
1019 {
1020         log(DEBUG,"ALLBUTONE: Comes from %s SHOULD NOT go back to %s",prefix.c_str(),omit.c_str());
1021         // TODO: Special stuff with privmsg and notice
1022         std::string FullLine = ":" + prefix + " " + command;
1023         for (unsigned int x = 0; x < params.size(); x++)
1024         {
1025                 FullLine = FullLine + " " + params[x];
1026         }
1027         for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1028         {
1029                 TreeServer* Route = TreeRoot->GetChild(x);
1030                 // Send the line IF:
1031                 // The route has a socket (its a direct connection)
1032                 // The route isnt the one to be omitted
1033                 // The route isnt the path to the one to be omitted
1034                 if ((Route->GetSocket()) && (Route->GetName() != omit) && (BestRouteTo(omit) != Route))
1035                 {
1036                         TreeSocket* Sock = Route->GetSocket();
1037                         log(DEBUG,"Sending to %s",Route->GetName().c_str());
1038                         Sock->WriteLine(FullLine);
1039                 }
1040         }
1041         return true;
1042 }
1043
1044 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params)
1045 {
1046         std::string FullLine = ":" + prefix + " " + command;
1047         for (unsigned int x = 0; x < params.size(); x++)
1048         {
1049                 FullLine = FullLine + " " + params[x];
1050         }
1051         for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1052         {
1053                 TreeServer* Route = TreeRoot->GetChild(x);
1054                 if (Route->GetSocket())
1055                 {
1056                         TreeSocket* Sock = Route->GetSocket();
1057                         Sock->WriteLine(FullLine);
1058                 }
1059         }
1060         return true;
1061 }
1062
1063 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target)
1064 {
1065         TreeServer* Route = BestRouteTo(target);
1066         if (Route)
1067         {
1068                 std::string FullLine = ":" + prefix + " " + command;
1069                 for (unsigned int x = 0; x < params.size(); x++)
1070                 {
1071                         FullLine = FullLine + " " + params[x];
1072                 }
1073                 if (Route->GetSocket())
1074                 {
1075                         TreeSocket* Sock = Route->GetSocket();
1076                         Sock->WriteLine(FullLine);
1077                 }
1078                 return true;
1079         }
1080         else
1081         {
1082                 log(DEBUG,"Could not route message with target %s: %s",target.c_str(),command.c_str());
1083                 return true;
1084         }
1085 }
1086
1087
1088 class ModuleSpanningTree : public Module
1089 {
1090         std::vector<TreeSocket*> Bindings;
1091         int line;
1092
1093  public:
1094
1095         void ReadConfiguration(bool rebind)
1096         {
1097                 if (rebind)
1098                 {
1099                         for (int j =0; j < Conf->Enumerate("bind"); j++)
1100                         {
1101                                 std::string Type = Conf->ReadValue("bind","type",j);
1102                                 std::string IP = Conf->ReadValue("bind","address",j);
1103                                 long Port = Conf->ReadInteger("bind","port",j,true);
1104                                 if (Type == "servers")
1105                                 {
1106                                         if (IP == "*")
1107                                         {
1108                                                 IP = "";
1109                                         }
1110                                         TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
1111                                         if (listener->GetState() == I_LISTENING)
1112                                         {
1113                                                 Srv->AddSocket(listener);
1114                                                 Bindings.push_back(listener);
1115                                         }
1116                                         else
1117                                         {
1118                                                 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
1119                                                 listener->Close();
1120                                                 delete listener;
1121                                         }
1122                                 }
1123                         }
1124                 }
1125                 LinkBlocks.clear();
1126                 for (int j =0; j < Conf->Enumerate("link"); j++)
1127                 {
1128                         Link L;
1129                         L.Name = Conf->ReadValue("link","name",j);
1130                         L.IPAddr = Conf->ReadValue("link","ipaddr",j);
1131                         L.Port = Conf->ReadInteger("link","port",j,true);
1132                         L.SendPass = Conf->ReadValue("link","sendpass",j);
1133                         L.RecvPass = Conf->ReadValue("link","recvpass",j);
1134                         LinkBlocks.push_back(L);
1135                         log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
1136                 }
1137         }
1138
1139         ModuleSpanningTree()
1140         {
1141                 Srv = new Server;
1142                 Conf = new ConfigReader;
1143                 Bindings.clear();
1144
1145                 // Create the root of the tree
1146                 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
1147
1148                 ReadConfiguration(true);
1149         }
1150
1151         void ShowLinks(TreeServer* Current, userrec* user, int hops)
1152         {
1153                 std::string Parent = TreeRoot->GetName();
1154                 if (Current->GetParent())
1155                 {
1156                         Parent = Current->GetParent()->GetName();
1157                 }
1158                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1159                 {
1160                         ShowLinks(Current->GetChild(q),user,hops+1);
1161                 }
1162                 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
1163         }
1164
1165         void HandleLinks(char** parameters, int pcnt, userrec* user)
1166         {
1167                 ShowLinks(TreeRoot,user,0);
1168                 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
1169                 return;
1170         }
1171
1172         void HandleLusers(char** parameters, int pcnt, userrec* user)
1173         {
1174                 return;
1175         }
1176
1177         // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
1178
1179         void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
1180         {
1181                 if (line < 128)
1182                 {
1183                         for (int t = 0; t < depth; t++)
1184                         {
1185                                 matrix[line][t] = ' ';
1186                         }
1187                         strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
1188                         line++;
1189                         for (unsigned int q = 0; q < Current->ChildCount(); q++)
1190                         {
1191                                 ShowMap(Current->GetChild(q),user,depth+2,matrix);
1192                         }
1193                 }
1194         }
1195
1196         // Ok, prepare to be confused.
1197         // After much mulling over how to approach this, it struck me that
1198         // the 'usual' way of doing a /MAP isnt the best way. Instead of
1199         // keeping track of a ton of ascii characters, and line by line
1200         // under recursion working out where to place them using multiplications
1201         // and divisons, we instead render the map onto a backplane of characters
1202         // (a character matrix), then draw the branches as a series of "L" shapes
1203         // from the nodes. This is not only friendlier on CPU it uses less stack.
1204
1205         void HandleMap(char** parameters, int pcnt, userrec* user)
1206         {
1207                 // This array represents a virtual screen which we will
1208                 // "scratch" draw to, as the console device of an irc
1209                 // client does not provide for a proper terminal.
1210                 char matrix[128][80];
1211                 for (unsigned int t = 0; t < 128; t++)
1212                 {
1213                         matrix[t][0] = '\0';
1214                 }
1215                 line = 0;
1216                 // The only recursive bit is called here.
1217                 ShowMap(TreeRoot,user,0,matrix);
1218                 // Process each line one by one. The algorithm has a limit of
1219                 // 128 servers (which is far more than a spanning tree should have
1220                 // anyway, so we're ok). This limit can be raised simply by making
1221                 // the character matrix deeper, 128 rows taking 10k of memory.
1222                 for (int l = 1; l < line; l++)
1223                 {
1224                         // scan across the line looking for the start of the
1225                         // servername (the recursive part of the algorithm has placed
1226                         // the servers at indented positions depending on what they
1227                         // are related to)
1228                         int first_nonspace = 0;
1229                         while (matrix[l][first_nonspace] == ' ')
1230                         {
1231                                 first_nonspace++;
1232                         }
1233                         first_nonspace--;
1234                         // Draw the `- (corner) section: this may be overwritten by
1235                         // another L shape passing along the same vertical pane, becoming
1236                         // a |- (branch) section instead.
1237                         matrix[l][first_nonspace] = '-';
1238                         matrix[l][first_nonspace-1] = '`';
1239                         int l2 = l - 1;
1240                         // Draw upwards until we hit the parent server, causing possibly
1241                         // other corners (`-) to become branches (|-)
1242                         while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
1243                         {
1244                                 matrix[l2][first_nonspace-1] = '|';
1245                                 l2--;
1246                         }
1247                 }
1248                 // dump the whole lot to the user. This is the easy bit, honest.
1249                 for (int t = 0; t < line; t++)
1250                 {
1251                         WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
1252                 }
1253                 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
1254                 return;
1255         }
1256
1257         int HandleSquit(char** parameters, int pcnt, userrec* user)
1258         {
1259                 return 1;
1260         }
1261
1262         int HandleConnect(char** parameters, int pcnt, userrec* user)
1263         {
1264                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1265                 {
1266                         if (Srv->MatchText(x->Name.c_str(),parameters[0]))
1267                         {
1268                                 WriteServ(user->fd,"NOTICE %s :*** CONNECT: Connecting to server: %s (%s:%d)",user->nick,x->Name.c_str(),x->IPAddr.c_str(),x->Port);
1269                                 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1270                                 Srv->AddSocket(newsocket);
1271                                 return 1;
1272                         }
1273                 }
1274                 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No matching server could be found in the config file.",user->nick);
1275                 return 1;
1276         }
1277
1278         virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
1279         {
1280                 if (command == "CONNECT")
1281                 {
1282                         return this->HandleConnect(parameters,pcnt,user);
1283                 }
1284                 else if (command == "SQUIT")
1285                 {
1286                         return this->HandleSquit(parameters,pcnt,user);
1287                 }
1288                 else if (command == "MAP")
1289                 {
1290                         this->HandleMap(parameters,pcnt,user);
1291                         return 1;
1292                 }
1293                 else if (command == "LUSERS")
1294                 {
1295                         this->HandleLusers(parameters,pcnt,user);
1296                         return 1;
1297                 }
1298                 else if (command == "LINKS")
1299                 {
1300                         this->HandleLinks(parameters,pcnt,user);
1301                         return 1;
1302                 }
1303                 return 0;
1304         }
1305
1306         virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
1307         {
1308                 if (target_type == TYPE_USER)
1309                 {
1310                         userrec* d = (userrec*)dest;
1311                         if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1312                         {
1313                                 std::deque<std::string> params;
1314                                 params.clear();
1315                                 params.push_back(d->nick);
1316                                 params.push_back(":"+text);
1317                                 DoOneToOne(user->nick,"NOTICE",params,d->server);
1318                         }
1319                 }
1320                 else
1321                 {
1322                         if (std::string(user->server) == Srv->GetServerName())
1323                         {
1324                                 chanrec *c = (chanrec*)dest;
1325                                 std::deque<std::string> params;
1326                                 params.push_back(c->name);
1327                                 params.push_back(":"+text);
1328                                 DoOneToMany(user->nick,"NOTICE",params);
1329                         }
1330                 }
1331         }
1332
1333         virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
1334         {
1335                 if (target_type == TYPE_USER)
1336                 {
1337                         // route private messages which are targetted at clients only to the server
1338                         // which needs to receive them
1339                         userrec* d = (userrec*)dest;
1340                         if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1341                         {
1342                                 std::deque<std::string> params;
1343                                 params.clear();
1344                                 params.push_back(d->nick);
1345                                 params.push_back(":"+text);
1346                                 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
1347                         }
1348                 }
1349                 else
1350                 {
1351                         if (std::string(user->server) == Srv->GetServerName())
1352                         {
1353                                 chanrec *c = (chanrec*)dest;
1354                                 std::deque<std::string> params;
1355                                 params.push_back(c->name);
1356                                 params.push_back(":"+text);
1357                                 DoOneToMany(user->nick,"PRIVMSG",params);
1358                         }
1359                 }
1360         }
1361
1362         virtual void OnUserJoin(userrec* user, chanrec* channel)
1363         {
1364                 // Only do this for local users
1365                 if (std::string(user->server) == Srv->GetServerName())
1366                 {
1367                         log(DEBUG,"**** User on %s JOINS %s",user->server,channel->name);
1368                         std::deque<std::string> params;
1369                         params.clear();
1370                         params.push_back(channel->name);
1371                         if (*channel->key)
1372                         {
1373                                 log(DEBUG,"**** With key %s",channel->key);
1374                                 // if the channel has a key, force the join by emulating the key.
1375                                 params.push_back(channel->key);
1376                         }
1377                         DoOneToMany(user->nick,"JOIN",params);
1378                 }
1379         }
1380
1381         virtual void OnUserPart(userrec* user, chanrec* channel)
1382         {
1383                 if (std::string(user->server) == Srv->GetServerName())
1384                 {
1385                         log(DEBUG,"**** User on %s PARTS %s",user->server,channel->name);
1386                         std::deque<std::string> params;
1387                         params.clear();
1388                         params.push_back(channel->name);
1389                         DoOneToMany(user->nick,"PART",params);
1390                 }
1391         }
1392
1393         virtual void OnUserConnect(userrec* user)
1394         {
1395                 char agestr[MAXBUF];
1396                 if (std::string(user->server) == Srv->GetServerName())
1397                 {
1398                         log(DEBUG,"**** User on %s CONNECTS: %s",user->server,user->nick);
1399                         std::deque<std::string> params;
1400                         snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
1401                         params.clear();
1402                         params.push_back(agestr);
1403                         params.push_back(user->nick);
1404                         params.push_back(user->host);
1405                         params.push_back(user->dhost);
1406                         params.push_back(user->ident);
1407                         params.push_back("+"+std::string(user->modes));
1408                         params.push_back(user->ip);
1409                         params.push_back(":"+std::string(user->fullname));
1410                         DoOneToMany(Srv->GetServerName(),"NICK",params);
1411                 }
1412         }
1413
1414         virtual void OnUserQuit(userrec* user, std::string reason)
1415         {
1416                 if (std::string(user->server) == Srv->GetServerName())
1417                 {
1418                         log(DEBUG,"**** User on %s QUITS: %s",user->server,user->nick);
1419                         std::deque<std::string> params;
1420                         params.push_back(":"+reason);
1421                         DoOneToMany(user->nick,"QUIT",params);
1422                 }
1423         }
1424
1425         virtual void OnUserPostNick(userrec* user, std::string oldnick)
1426         {
1427                 if (std::string(user->server) == Srv->GetServerName())
1428                 {
1429                         log(DEBUG,"**** User on %s changes NICK: %s",user->server,user->nick);
1430                         std::deque<std::string> params;
1431                         params.push_back(user->nick);
1432                         DoOneToMany(oldnick,"NICK",params);
1433                 }
1434         }
1435
1436         virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
1437         {
1438                 if (std::string(source->server) == Srv->GetServerName())
1439                 {
1440                         log(DEBUG,"**** User on %s KICKs: %s %s",source->server,source->nick,user->nick);
1441                         std::deque<std::string> params;
1442                         params.push_back(chan->name);
1443                         params.push_back(user->nick);
1444                         params.push_back(":"+reason);
1445                         DoOneToMany(source->nick,"KICK",params);
1446                 }
1447         }
1448
1449         // note: the protocol does not allow direct umode +o except
1450         // via NICK with 8 params. sending OPERTYPE infers +o modechange
1451         // locally.
1452         virtual void OnOper(userrec* user, std::string opertype)
1453         {
1454                 if (std::string(user->server) == Srv->GetServerName())
1455                 {
1456                         std::deque<std::string> params;
1457                         params.push_back(opertype);
1458                         DoOneToMany(user->nick,"OPERTYPE",params);
1459                 }
1460         }
1461
1462         virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
1463         {
1464                 log(DEBUG,"*** ONMODE TRIGGER");
1465                 if (std::string(user->server) == Srv->GetServerName())
1466                 {
1467                         log(DEBUG,"*** LOCAL");
1468                         if (target_type == TYPE_USER)
1469                         {
1470                                 userrec* u = (userrec*)dest;
1471                                 std::deque<std::string> params;
1472                                 params.push_back(u->nick);
1473                                 params.push_back(text);
1474                                 DoOneToMany(user->nick,"MODE",params);
1475                         }
1476                         else
1477                         {
1478                                 chanrec* c = (chanrec*)dest;
1479                                 std::deque<std::string> params;
1480                                 params.push_back(c->name);
1481                                 params.push_back(text);
1482                                 DoOneToMany(user->nick,"MODE",params);
1483                         }
1484                 }
1485         }
1486
1487         virtual ~ModuleSpanningTree()
1488         {
1489                 delete Srv;
1490         }
1491
1492         virtual Version GetVersion()
1493         {
1494                 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
1495         }
1496 };
1497
1498
1499 class ModuleSpanningTreeFactory : public ModuleFactory
1500 {
1501  public:
1502         ModuleSpanningTreeFactory()
1503         {
1504         }
1505         
1506         ~ModuleSpanningTreeFactory()
1507         {
1508         }
1509         
1510         virtual Module * CreateModule()
1511         {
1512                 return new ModuleSpanningTree;
1513         }
1514         
1515 };
1516
1517
1518 extern "C" void * init_module( void )
1519 {
1520         return new ModuleSpanningTreeFactory;
1521 }
1522