]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree.cpp
f2ffc111643bbd07480d3184a8c7094e6bb6fb37
[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 ForceTopic(std::string source, std::deque<std::string> params)
453         {
454                 // FTOPIC %s %lu %s :%s
455                 if (params.size() != 4)
456                         return true;
457                 std::string channel = params[0];
458                 time_t ts = atoi(params[1].c_str());
459                 std::string setby = params[2];
460                 std::string topic = params[3];
461
462                 chanrec* c = Srv->FindChannel(channel);
463                 if (c)
464                 {
465                         if ((ts >= c->topicset) || (!*c->topic))
466                         {
467                                 strlcpy(c->topic,topic.c_str(),MAXTOPIC);
468                                 strlcpy(c->setby,setby.c_str(),NICKMAX);
469                                 c->topicset = ts;
470                                 WriteChannelWithServ((char*)source.c_str(), c, "TOPIC %s :%s", c->name, c->topic);
471                         }
472                         
473                 }
474                 
475                 // all done, send it on its way
476                 params[3] = ":" + params[3];
477                 DoOneToAllButSender(source,"FTOPIC",params,source);
478
479                 return true;
480         }
481
482         bool ForceJoin(std::string source, std::deque<std::string> params)
483         {
484                 if (params.size() < 1)
485                         return true;
486                 for (unsigned int channelnum = 0; channelnum < params.size(); channelnum++)
487                 {
488                         // process one channel at a time, applying modes.
489                         char* channel = (char*)params[channelnum].c_str();
490                         char permissions = *channel;
491                         char* mode = NULL;
492                         switch (permissions)
493                         {
494                                 case '@':
495                                         channel++;
496                                         mode = "+o";
497                                 break;
498                                 case '%':
499                                         channel++;
500                                         mode = "+h";
501                                 break;
502                                 case '+':
503                                         channel++;
504                                         mode = "+v";
505                                 break;
506                         }
507                         userrec* who = Srv->FindNick(source);
508                         if (who)
509                         {
510                                 char* key = "";
511                                 chanrec* chan = Srv->FindChannel(channel);
512                                 if ((chan) && (*chan->key))
513                                 {
514                                         key = chan->key;
515                                 }
516                                 Srv->JoinUserToChannel(who,channel,key);
517                                 if (mode)
518                                 {
519                                         char* modelist[3];
520                                         modelist[0] = channel;
521                                         modelist[1] = mode;
522                                         modelist[2] = who->nick;
523                                         Srv->SendMode(modelist,3,who);
524                                 }
525                                 DoOneToAllButSender(source,"FJOIN",params,who->server);
526                         }
527                 }
528                 return true;
529         }
530
531         bool IntroduceClient(std::string source, std::deque<std::string> params)
532         {
533                 if (params.size() < 8)
534                         return true;
535                 // NICK age nick host dhost ident +modes ip :gecos
536                 //       0   1    2    3      4     5    6   7
537                 std::string nick = params[1];
538                 std::string host = params[2];
539                 std::string dhost = params[3];
540                 std::string ident = params[4];
541                 time_t age = atoi(params[0].c_str());
542                 std::string modes = params[5];
543                 if (*(modes.c_str()) == '+')
544                 {
545                         char* m = (char*)modes.c_str();
546                         m++;
547                         modes = m;
548                 }
549                 std::string ip = params[6];
550                 std::string gecos = params[7];
551                 char* tempnick = (char*)nick.c_str();
552                 log(DEBUG,"Introduce client %s!%s@%s",tempnick,ident.c_str(),host.c_str());
553                 
554                 user_hash::iterator iter;
555                 iter = clientlist.find(tempnick);
556                 if (iter != clientlist.end())
557                 {
558                         // nick collision
559                         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);
560                         if (age <= iter->second->age)
561                         {
562                                 log (DEBUG,"*** COLLISION: Remote client is older");
563                                 // remote client is older
564                                 // if hosts are identical, kill the remote,
565                                 // else kill the local. We must send KILL for
566                                 // removal of remote users.
567                                 if (!strcmp(iter->second->host,host.c_str()))
568                                 {
569                                         // kill the remote by sending KILL,
570                                         // and ABORT to stop it being introduced here.
571                                         log(DEBUG,"**** LOCATION ONE");
572                                         this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Killed (Nickname collision from "+Srv->GetServerName()+")");
573                                         return true;
574                                 }
575                                 else
576                                 {
577                                         log(DEBUG,"*** LOCATION TWO");
578                                         // kill our local and continue to let the remote be introduced
579                                         Srv->QuitUser(iter->second,"Killed (Nickname collision from "+source+")");
580                                 }
581                         }
582                         else
583                         {
584                                 log(DEBUG,"*** COLLISION: Remote client is newer");
585                                 // remote is newer, kill it and bail to stop it being introduced
586                                 this->WriteLine(":"+Srv->GetServerName()+" KILL "+tempnick+" :Killed (Nickname collision from "+Srv->GetServerName()+")");
587                                 return true;
588                         }
589                 }
590                 
591                 clientlist[tempnick] = new userrec();
592                 clientlist[tempnick]->fd = FD_MAGIC_NUMBER;
593                 strlcpy(clientlist[tempnick]->nick, tempnick,NICKMAX);
594                 strlcpy(clientlist[tempnick]->host, host.c_str(),160);
595                 strlcpy(clientlist[tempnick]->dhost, dhost.c_str(),160);
596                 clientlist[tempnick]->server = (char*)FindServerNamePtr(source.c_str());
597                 strlcpy(clientlist[tempnick]->ident, ident.c_str(),IDENTMAX);
598                 strlcpy(clientlist[tempnick]->fullname, gecos.c_str(),MAXGECOS);
599                 clientlist[tempnick]->registered = 7;
600                 clientlist[tempnick]->signon = age;
601                 strlcpy(clientlist[tempnick]->ip,ip.c_str(),16);
602                 for (int i = 0; i < MAXCHANS; i++)
603                 {
604                         clientlist[tempnick]->chans[i].channel = NULL;
605                         clientlist[tempnick]->chans[i].uc_modes = 0;
606                 }
607                 params[7] = ":" + params[7];
608                 DoOneToAllButSender(source,"NICK",params,source);
609                 return true;
610         }
611
612         void SendChannelModes(TreeServer* Current)
613         {
614                 char data[MAXBUF];
615                 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
616                 {
617                         snprintf(data,MAXBUF,":%s FMODE %s +%s",Srv->GetServerName().c_str(),c->second->name,chanmodes(c->second));
618                         this->WriteLine(data);
619                         if (*c->second->topic)
620                         {
621                                 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);
622                                 this->WriteLine(data);
623                         }
624                         for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
625                         {
626                                 snprintf(data,MAXBUF,":%s FMODE %s +b %s",Srv->GetServerName().c_str(),c->second->name,b->data);
627                                 this->WriteLine(data);
628                         }
629                 }
630         }
631
632         // send all users and their channels
633         void SendUsers(TreeServer* Current)
634         {
635                 char data[MAXBUF];
636                 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
637                 {
638                         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);
639                         this->WriteLine(data);
640                         if (strchr(u->second->modes,'o'))
641                         {
642                                 this->WriteLine(":"+std::string(u->second->nick)+" OPERTYPE "+std::string(u->second->oper));
643                         }
644                         char* chl = chlist(u->second,u->second);
645                         if (*chl)
646                         {
647                                 this->WriteLine(":"+std::string(u->second->nick)+" FJOIN "+std::string(chl));
648                         }
649                 }
650         }
651
652         void DoBurst(TreeServer* s)
653         {
654                 log(DEBUG,"Beginning network burst");
655                 Srv->SendOpers("*** Bursting to "+s->GetName()+".");
656                 this->WriteLine("BURST");
657                 // Send server tree
658                 this->SendServers(TreeRoot,s,1);
659                 // Send users and their channels
660                 this->SendUsers(s);
661                 // TODO: Send everything else (channel modes etc)
662                 this->SendChannelModes(s);
663                 this->WriteLine("ENDBURST");
664         }
665
666         virtual bool OnDataReady()
667         {
668                 char* data = this->Read();
669                 if (data)
670                 {
671                         this->in_buffer += data;
672                         while (in_buffer.find("\n") != std::string::npos)
673                         {
674                                 char* line = (char*)in_buffer.c_str();
675                                 std::string ret = "";
676                                 while ((*line != '\n') && (strlen(line)))
677                                 {
678                                         ret = ret + *line;
679                                         line++;
680                                 }
681                                 if ((*line == '\n') || (*line == '\r'))
682                                         line++;
683                                 in_buffer = line;
684                                 if (!this->ProcessLine(ret))
685                                 {
686                                         return false;
687                                 }
688                         }
689                 }
690                 return (data != NULL);
691         }
692
693         int WriteLine(std::string line)
694         {
695                 return this->Write(line + "\r\n");
696         }
697
698         bool Error(std::deque<std::string> params)
699         {
700                 if (params.size() < 1)
701                         return false;
702                 std::string Errmsg = params[0];
703                 std::string SName = myhost;
704                 if (InboundServerName != "")
705                 {
706                         SName = InboundServerName;
707                 }
708                 Srv->SendOpers("*** ERROR from "+SName+": "+Errmsg);
709                 // we will return false to cause the socket to close.
710                 return false;
711         }
712
713         bool OperType(std::string prefix, std::deque<std::string> params)
714         {
715                 if (params.size() != 1)
716                         return true;
717                 std::string opertype = params[0];
718                 userrec* u = Srv->FindNick(prefix);
719                 if (u)
720                 {
721                         strlcpy(u->oper,opertype.c_str(),NICKMAX);
722                         if (!strchr(u->modes,'o'))
723                         {
724                                 strcat(u->modes,"o");
725                         }
726                         DoOneToAllButSender(u->server,"OPERTYPE",params,u->server);
727                 }
728                 return true;
729         }
730
731         bool RemoteKill(std::string prefix, std::deque<std::string> params)
732         {
733                 if (params.size() != 2)
734                         return true;
735                 std::string nick = params[0];
736                 std::string reason = params[1];
737                 userrec* u = Srv->FindNick(prefix);
738                 userrec* who = Srv->FindNick(nick);
739                 if (who)
740                 {
741                         std::string sourceserv = prefix;
742                         if (u)
743                         {
744                                 sourceserv = u->server;
745                         }
746                         params[1] = ":" + params[1];
747                         DoOneToAllButSender(prefix,"KILL",params,sourceserv);
748                         Srv->QuitUser(who,reason);
749                 }
750                 return true;
751         }
752
753         bool RemoteServer(std::string prefix, std::deque<std::string> params)
754         {
755                 if (params.size() < 4)
756                         return false;
757                 std::string servername = params[0];
758                 std::string password = params[1];
759                 int hops = atoi(params[2].c_str());
760                 std::string description = params[3];
761                 if (!hops)
762                 {
763                         this->WriteLine("ERROR :Protocol error - Introduced remote server with incorrect hopcount!");
764                         return false;
765                 }
766                 TreeServer* ParentOfThis = FindServer(prefix);
767                 if (!ParentOfThis)
768                 {
769                         this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
770                         return false;
771                 }
772                 TreeServer* Node = new TreeServer(servername,description,ParentOfThis,NULL);
773                 ParentOfThis->AddChild(Node);
774                 params[3] = ":" + params[3];
775                 DoOneToAllButSender(prefix,"SERVER",params,prefix);
776                 Srv->SendOpers("*** Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
777                 return true;
778         }
779
780         bool Outbound_Reply_Server(std::deque<std::string> params)
781         {
782                 if (params.size() < 4)
783                         return false;
784                 std::string servername = params[0];
785                 std::string password = params[1];
786                 int hops = atoi(params[2].c_str());
787                 if (hops)
788                 {
789                         this->WriteLine("ERROR :Server too far away for authentication");
790                         return false;
791                 }
792                 std::string description = params[3];
793                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
794                 {
795                         if ((x->Name == servername) && (x->RecvPass == password))
796                         {
797                                 // Begin the sync here. this kickstarts the
798                                 // other side, waiting in WAIT_AUTH_2 state,
799                                 // into starting their burst, as it shows
800                                 // that we're happy.
801                                 this->LinkState = CONNECTED;
802                                 // we should add the details of this server now
803                                 // to the servers tree, as a child of the root
804                                 // node.
805                                 TreeServer* Node = new TreeServer(servername,description,TreeRoot,this);
806                                 TreeRoot->AddChild(Node);
807                                 params[3] = ":" + params[3];
808                                 DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,servername);
809                                 this->DoBurst(Node);
810                                 return true;
811                         }
812                 }
813                 this->WriteLine("ERROR :Invalid credentials");
814                 return false;
815         }
816
817         bool Inbound_Server(std::deque<std::string> params)
818         {
819                 if (params.size() < 4)
820                         return false;
821                 std::string servername = params[0];
822                 std::string password = params[1];
823                 int hops = atoi(params[2].c_str());
824                 if (hops)
825                 {
826                         this->WriteLine("ERROR :Server too far away for authentication");
827                         return false;
828                 }
829                 std::string description = params[3];
830                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
831                 {
832                         if ((x->Name == servername) && (x->RecvPass == password))
833                         {
834                                 Srv->SendOpers("*** Verified incoming server connection from \002"+servername+"\002["+this->GetIP()+"] ("+description+")");
835                                 this->InboundServerName = servername;
836                                 this->InboundDescription = description;
837                                 // this is good. Send our details: Our server name and description and hopcount of 0,
838                                 // along with the sendpass from this block.
839                                 this->WriteLine("SERVER "+Srv->GetServerName()+" "+x->SendPass+" 0 :"+Srv->GetServerDescription());
840                                 // move to the next state, we are now waiting for THEM.
841                                 this->LinkState = WAIT_AUTH_2;
842                                 return true;
843                         }
844                 }
845                 this->WriteLine("ERROR :Invalid credentials");
846                 return false;
847         }
848
849         std::deque<std::string> Split(std::string line, bool stripcolon)
850         {
851                 std::deque<std::string> n;
852                 std::stringstream s(line);
853                 std::string param = "";
854                 n.clear();
855                 int item = 0;
856                 while (!s.eof())
857                 {
858                         s >> param;
859                         if ((param != "") && (param != "\n"))
860                         {
861                                 if ((param.c_str()[0] == ':') && (item))
862                                 {
863                                         char* str = (char*)param.c_str();
864                                         str++;
865                                         param = str;
866                                         std::string append;
867                                         while (!s.eof())
868                                         {
869                                                 append = "";
870                                                 s >> append;
871                                                 if (append != "")
872                                                 {
873                                                         param = param + " " + append;
874                                                 }
875                                         }
876                                 }
877                                 item++;
878                                 n.push_back(param);
879                         }
880                 }
881                 return n;
882         }
883
884         bool ProcessLine(std::string line)
885         {
886                 char* l = (char*)line.c_str();
887                 while ((strlen(l)) && (l[strlen(l)-1] == '\r') || (l[strlen(l)-1] == '\n'))
888                         l[strlen(l)-1] = '\0';
889                 line = l;
890                 if (line == "")
891                         return true;
892                 Srv->Log(DEBUG,"inbound-line: '"+line+"'");
893                 std::deque<std::string> params = this->Split(line,true);
894                 std::string command = "";
895                 std::string prefix = "";
896                 if (((params[0].c_str())[0] == ':') && (params.size() > 1))
897                 {
898                         prefix = params[0];
899                         command = params[1];
900                         char* pref = (char*)prefix.c_str();
901                         prefix = ++pref;
902                         params.pop_front();
903                         params.pop_front();
904                 }
905                 else
906                 {
907                         prefix = "";
908                         command = params[0];
909                         params.pop_front();
910                 }
911                 
912                 switch (this->LinkState)
913                 {
914                         TreeServer* Node;
915                         
916                         case WAIT_AUTH_1:
917                                 // Waiting for SERVER command from remote server. Server initiating
918                                 // the connection sends the first SERVER command, listening server
919                                 // replies with theirs if its happy, then if the initiator is happy,
920                                 // it starts to send its net sync, which starts the merge, otherwise
921                                 // it sends an ERROR.
922                                 if (command == "SERVER")
923                                 {
924                                         return this->Inbound_Server(params);
925                                 }
926                                 else if (command == "ERROR")
927                                 {
928                                         return this->Error(params);
929                                 }
930                         break;
931                         case WAIT_AUTH_2:
932                                 // Waiting for start of other side's netmerge to say they liked our
933                                 // password.
934                                 if (command == "SERVER")
935                                 {
936                                         // cant do this, they sent it to us in the WAIT_AUTH_1 state!
937                                         // silently ignore.
938                                         return true;
939                                 }
940                                 else if (command == "BURST")
941                                 {
942                                         this->LinkState = CONNECTED;
943                                         Node = new TreeServer(InboundServerName,InboundDescription,TreeRoot,this);
944                                         TreeRoot->AddChild(Node);
945                                         params.clear();
946                                         params.push_back(InboundServerName);
947                                         params.push_back("*");
948                                         params.push_back("1");
949                                         params.push_back(":"+InboundDescription);
950                                         DoOneToAllButSender(TreeRoot->GetName(),"SERVER",params,InboundServerName);
951                                         this->DoBurst(Node);
952                                 }
953                                 else if (command == "ERROR")
954                                 {
955                                         return this->Error(params);
956                                 }
957                                 
958                         break;
959                         case LISTENER:
960                                 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
961                                 return false;
962                         break;
963                         case CONNECTING:
964                                 if (command == "SERVER")
965                                 {
966                                         // another server we connected to, which was in WAIT_AUTH_1 state,
967                                         // has just sent us their credentials. If we get this far, theyre
968                                         // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
969                                         // if we're happy with this, we should send our netburst which
970                                         // kickstarts the merge.
971                                         return this->Outbound_Reply_Server(params);
972                                 }
973                         break;
974                         case CONNECTED:
975                                 // This is the 'authenticated' state, when all passwords
976                                 // have been exchanged and anything past this point is taken
977                                 // as gospel.
978                                 std::string target = "";
979                                 if ((command == "NICK") && (params.size() > 1))
980                                 {
981                                         return this->IntroduceClient(prefix,params);
982                                 }
983                                 else if (command == "FJOIN")
984                                 {
985                                         return this->ForceJoin(prefix,params);
986                                 }
987                                 else if (command == "SERVER")
988                                 {
989                                         return this->RemoteServer(prefix,params);
990                                 }
991                                 else if (command == "OPERTYPE")
992                                 {
993                                         return this->OperType(prefix,params);
994                                 }
995                                 else if (command == "FMODE")
996                                 {
997                                         return this->ForceMode(prefix,params);
998                                 }
999                                 else if (command == "KILL")
1000                                 {
1001                                         return this->RemoteKill(prefix,params);
1002                                 }
1003                                 else if (command == "FTOPIC")
1004                                 {
1005                                         return this->ForceTopic(prefix,params);
1006                                 }
1007                                 else if (command == "SQUIT")
1008                                 {
1009                                         if (params.size() == 2)
1010                                         {
1011                                                 this->Squit(FindServer(params[0]),params[1]);
1012                                         }
1013                                         return true;
1014                                 }
1015                                 else
1016                                 {
1017                                         // not a special inter-server command.
1018                                         // Emulate the actual user doing the command,
1019                                         // this saves us having a huge ugly parser.
1020                                         userrec* who = Srv->FindNick(prefix);
1021                                         std::string sourceserv = this->myhost;
1022                                         if (this->InboundServerName != "")
1023                                         {
1024                                                 sourceserv = this->InboundServerName;
1025                                         }
1026                                         if (who)
1027                                         {
1028                                                 // its a user
1029                                                 target = who->server;
1030                                                 char* strparams[127];
1031                                                 for (unsigned int q = 0; q < params.size(); q++)
1032                                                 {
1033                                                         strparams[q] = (char*)params[q].c_str();
1034                                                 }
1035                                                 log(DEBUG,"*** CALL COMMAND HANDLER FOR %s, SOURCE: '%s'",command.c_str(),who->nick);
1036                                                 Srv->CallCommandHandler(command, strparams, params.size(), who);
1037                                         }
1038                                         else
1039                                         {
1040                                                 // its not a user. Its either a server, or somethings screwed up.
1041                                                 if (IsServer(prefix))
1042                                                 {
1043                                                         target = Srv->GetServerName();
1044                                                 }
1045                                                 else
1046                                                 {
1047                                                         log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
1048                                                         return true;
1049                                                 }
1050                                         }
1051                                         return DoOneToAllButSenderRaw(line,sourceserv);
1052
1053                                 }
1054                                 return true;
1055                         break;  
1056                 }
1057                 return true;
1058         }
1059
1060         virtual void OnTimeout()
1061         {
1062                 if (this->LinkState == CONNECTING)
1063                 {
1064                         Srv->SendOpers("*** CONNECT: Connection to \002"+myhost+"\002 timed out.");
1065                 }
1066         }
1067
1068         virtual void OnClose()
1069         {
1070                 // Connection closed.
1071                 // If the connection is fully up (state CONNECTED)
1072                 // then propogate a netsplit to all peers.
1073                 std::string quitserver = this->myhost;
1074                 if (this->InboundServerName != "")
1075                 {
1076                         quitserver = this->InboundServerName;
1077                 }
1078                 TreeServer* s = FindServer(quitserver);
1079                 if (s)
1080                 {
1081                         Squit(s,"Remote host closed the connection");
1082                 }
1083         }
1084
1085         virtual int OnIncomingConnection(int newsock, char* ip)
1086         {
1087                 TreeSocket* s = new TreeSocket(newsock, ip);
1088                 Srv->AddSocket(s);
1089                 return true;
1090         }
1091 };
1092
1093 bool DoOneToAllButSenderRaw(std::string data,std::string omit)
1094 {
1095         for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1096         {
1097                 TreeServer* Route = TreeRoot->GetChild(x);
1098                 if ((Route->GetSocket()) && (Route->GetName() != omit) && (BestRouteTo(omit) != Route))
1099                 {
1100                         TreeSocket* Sock = Route->GetSocket();
1101                         log(DEBUG,"Sending RAW to %s",Route->GetName().c_str());
1102                         Sock->WriteLine(data);
1103                 }
1104         }
1105         return true;
1106 }
1107
1108 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit)
1109 {
1110         log(DEBUG,"ALLBUTONE: Comes from %s SHOULD NOT go back to %s",prefix.c_str(),omit.c_str());
1111         // TODO: Special stuff with privmsg and notice
1112         std::string FullLine = ":" + prefix + " " + command;
1113         for (unsigned int x = 0; x < params.size(); x++)
1114         {
1115                 FullLine = FullLine + " " + params[x];
1116         }
1117         for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1118         {
1119                 TreeServer* Route = TreeRoot->GetChild(x);
1120                 // Send the line IF:
1121                 // The route has a socket (its a direct connection)
1122                 // The route isnt the one to be omitted
1123                 // The route isnt the path to the one to be omitted
1124                 if ((Route->GetSocket()) && (Route->GetName() != omit) && (BestRouteTo(omit) != Route))
1125                 {
1126                         TreeSocket* Sock = Route->GetSocket();
1127                         log(DEBUG,"Sending to %s",Route->GetName().c_str());
1128                         Sock->WriteLine(FullLine);
1129                 }
1130         }
1131         return true;
1132 }
1133
1134 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params)
1135 {
1136         std::string FullLine = ":" + prefix + " " + command;
1137         for (unsigned int x = 0; x < params.size(); x++)
1138         {
1139                 FullLine = FullLine + " " + params[x];
1140         }
1141         for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1142         {
1143                 TreeServer* Route = TreeRoot->GetChild(x);
1144                 if (Route->GetSocket())
1145                 {
1146                         TreeSocket* Sock = Route->GetSocket();
1147                         Sock->WriteLine(FullLine);
1148                 }
1149         }
1150         return true;
1151 }
1152
1153 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target)
1154 {
1155         TreeServer* Route = BestRouteTo(target);
1156         if (Route)
1157         {
1158                 std::string FullLine = ":" + prefix + " " + command;
1159                 for (unsigned int x = 0; x < params.size(); x++)
1160                 {
1161                         FullLine = FullLine + " " + params[x];
1162                 }
1163                 if (Route->GetSocket())
1164                 {
1165                         TreeSocket* Sock = Route->GetSocket();
1166                         Sock->WriteLine(FullLine);
1167                 }
1168                 return true;
1169         }
1170         else
1171         {
1172                 log(DEBUG,"Could not route message with target %s: %s",target.c_str(),command.c_str());
1173                 return true;
1174         }
1175 }
1176
1177
1178 class ModuleSpanningTree : public Module
1179 {
1180         std::vector<TreeSocket*> Bindings;
1181         int line;
1182
1183  public:
1184
1185         void ReadConfiguration(bool rebind)
1186         {
1187                 if (rebind)
1188                 {
1189                         for (int j =0; j < Conf->Enumerate("bind"); j++)
1190                         {
1191                                 std::string Type = Conf->ReadValue("bind","type",j);
1192                                 std::string IP = Conf->ReadValue("bind","address",j);
1193                                 long Port = Conf->ReadInteger("bind","port",j,true);
1194                                 if (Type == "servers")
1195                                 {
1196                                         if (IP == "*")
1197                                         {
1198                                                 IP = "";
1199                                         }
1200                                         TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
1201                                         if (listener->GetState() == I_LISTENING)
1202                                         {
1203                                                 Srv->AddSocket(listener);
1204                                                 Bindings.push_back(listener);
1205                                         }
1206                                         else
1207                                         {
1208                                                 log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
1209                                                 listener->Close();
1210                                                 delete listener;
1211                                         }
1212                                 }
1213                         }
1214                 }
1215                 LinkBlocks.clear();
1216                 for (int j =0; j < Conf->Enumerate("link"); j++)
1217                 {
1218                         Link L;
1219                         L.Name = Conf->ReadValue("link","name",j);
1220                         L.IPAddr = Conf->ReadValue("link","ipaddr",j);
1221                         L.Port = Conf->ReadInteger("link","port",j,true);
1222                         L.SendPass = Conf->ReadValue("link","sendpass",j);
1223                         L.RecvPass = Conf->ReadValue("link","recvpass",j);
1224                         LinkBlocks.push_back(L);
1225                         log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
1226                 }
1227         }
1228
1229         ModuleSpanningTree()
1230         {
1231                 Srv = new Server;
1232                 Conf = new ConfigReader;
1233                 Bindings.clear();
1234
1235                 // Create the root of the tree
1236                 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
1237
1238                 ReadConfiguration(true);
1239         }
1240
1241         void ShowLinks(TreeServer* Current, userrec* user, int hops)
1242         {
1243                 std::string Parent = TreeRoot->GetName();
1244                 if (Current->GetParent())
1245                 {
1246                         Parent = Current->GetParent()->GetName();
1247                 }
1248                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1249                 {
1250                         ShowLinks(Current->GetChild(q),user,hops+1);
1251                 }
1252                 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
1253         }
1254
1255         void HandleLinks(char** parameters, int pcnt, userrec* user)
1256         {
1257                 ShowLinks(TreeRoot,user,0);
1258                 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
1259                 return;
1260         }
1261
1262         void HandleLusers(char** parameters, int pcnt, userrec* user)
1263         {
1264                 return;
1265         }
1266
1267         // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
1268
1269         void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
1270         {
1271                 if (line < 128)
1272                 {
1273                         for (int t = 0; t < depth; t++)
1274                         {
1275                                 matrix[line][t] = ' ';
1276                         }
1277                         strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
1278                         line++;
1279                         for (unsigned int q = 0; q < Current->ChildCount(); q++)
1280                         {
1281                                 ShowMap(Current->GetChild(q),user,depth+2,matrix);
1282                         }
1283                 }
1284         }
1285
1286         // Ok, prepare to be confused.
1287         // After much mulling over how to approach this, it struck me that
1288         // the 'usual' way of doing a /MAP isnt the best way. Instead of
1289         // keeping track of a ton of ascii characters, and line by line
1290         // under recursion working out where to place them using multiplications
1291         // and divisons, we instead render the map onto a backplane of characters
1292         // (a character matrix), then draw the branches as a series of "L" shapes
1293         // from the nodes. This is not only friendlier on CPU it uses less stack.
1294
1295         void HandleMap(char** parameters, int pcnt, userrec* user)
1296         {
1297                 // This array represents a virtual screen which we will
1298                 // "scratch" draw to, as the console device of an irc
1299                 // client does not provide for a proper terminal.
1300                 char matrix[128][80];
1301                 for (unsigned int t = 0; t < 128; t++)
1302                 {
1303                         matrix[t][0] = '\0';
1304                 }
1305                 line = 0;
1306                 // The only recursive bit is called here.
1307                 ShowMap(TreeRoot,user,0,matrix);
1308                 // Process each line one by one. The algorithm has a limit of
1309                 // 128 servers (which is far more than a spanning tree should have
1310                 // anyway, so we're ok). This limit can be raised simply by making
1311                 // the character matrix deeper, 128 rows taking 10k of memory.
1312                 for (int l = 1; l < line; l++)
1313                 {
1314                         // scan across the line looking for the start of the
1315                         // servername (the recursive part of the algorithm has placed
1316                         // the servers at indented positions depending on what they
1317                         // are related to)
1318                         int first_nonspace = 0;
1319                         while (matrix[l][first_nonspace] == ' ')
1320                         {
1321                                 first_nonspace++;
1322                         }
1323                         first_nonspace--;
1324                         // Draw the `- (corner) section: this may be overwritten by
1325                         // another L shape passing along the same vertical pane, becoming
1326                         // a |- (branch) section instead.
1327                         matrix[l][first_nonspace] = '-';
1328                         matrix[l][first_nonspace-1] = '`';
1329                         int l2 = l - 1;
1330                         // Draw upwards until we hit the parent server, causing possibly
1331                         // other corners (`-) to become branches (|-)
1332                         while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
1333                         {
1334                                 matrix[l2][first_nonspace-1] = '|';
1335                                 l2--;
1336                         }
1337                 }
1338                 // dump the whole lot to the user. This is the easy bit, honest.
1339                 for (int t = 0; t < line; t++)
1340                 {
1341                         WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
1342                 }
1343                 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
1344                 return;
1345         }
1346
1347         int HandleSquit(char** parameters, int pcnt, userrec* user)
1348         {
1349                 return 1;
1350         }
1351
1352         int HandleConnect(char** parameters, int pcnt, userrec* user)
1353         {
1354                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1355                 {
1356                         if (Srv->MatchText(x->Name.c_str(),parameters[0]))
1357                         {
1358                                 WriteServ(user->fd,"NOTICE %s :*** CONNECT: Connecting to server: %s (%s:%d)",user->nick,x->Name.c_str(),x->IPAddr.c_str(),x->Port);
1359                                 TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1360                                 Srv->AddSocket(newsocket);
1361                                 return 1;
1362                         }
1363                 }
1364                 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No matching server could be found in the config file.",user->nick);
1365                 return 1;
1366         }
1367
1368         virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
1369         {
1370                 if (command == "CONNECT")
1371                 {
1372                         return this->HandleConnect(parameters,pcnt,user);
1373                 }
1374                 else if (command == "SQUIT")
1375                 {
1376                         return this->HandleSquit(parameters,pcnt,user);
1377                 }
1378                 else if (command == "MAP")
1379                 {
1380                         this->HandleMap(parameters,pcnt,user);
1381                         return 1;
1382                 }
1383                 else if (command == "LUSERS")
1384                 {
1385                         this->HandleLusers(parameters,pcnt,user);
1386                         return 1;
1387                 }
1388                 else if (command == "LINKS")
1389                 {
1390                         this->HandleLinks(parameters,pcnt,user);
1391                         return 1;
1392                 }
1393                 return 0;
1394         }
1395
1396         virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
1397         {
1398                 if (std::string(source->server) == Srv->GetServerName())
1399                 {
1400                         std::deque<std::string> params;
1401                         params.push_back(dest->nick);
1402                         params.push_back(channel->name);
1403                         DoOneToMany(source->nick,"INVITE",params);
1404                 }
1405         }
1406
1407         virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
1408         {
1409                 std::deque<std::string> params;
1410                 params.push_back(chan->name);
1411                 params.push_back(":"+topic);
1412                 DoOneToMany(user->nick,"TOPIC",params);
1413         }
1414
1415         virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
1416         {
1417                 if (target_type == TYPE_USER)
1418                 {
1419                         userrec* d = (userrec*)dest;
1420                         if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1421                         {
1422                                 std::deque<std::string> params;
1423                                 params.clear();
1424                                 params.push_back(d->nick);
1425                                 params.push_back(":"+text);
1426                                 DoOneToOne(user->nick,"NOTICE",params,d->server);
1427                         }
1428                 }
1429                 else
1430                 {
1431                         if (std::string(user->server) == Srv->GetServerName())
1432                         {
1433                                 chanrec *c = (chanrec*)dest;
1434                                 std::deque<std::string> params;
1435                                 params.push_back(c->name);
1436                                 params.push_back(":"+text);
1437                                 DoOneToMany(user->nick,"NOTICE",params);
1438                         }
1439                 }
1440         }
1441
1442         virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
1443         {
1444                 if (target_type == TYPE_USER)
1445                 {
1446                         // route private messages which are targetted at clients only to the server
1447                         // which needs to receive them
1448                         userrec* d = (userrec*)dest;
1449                         if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1450                         {
1451                                 std::deque<std::string> params;
1452                                 params.clear();
1453                                 params.push_back(d->nick);
1454                                 params.push_back(":"+text);
1455                                 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
1456                         }
1457                 }
1458                 else
1459                 {
1460                         if (std::string(user->server) == Srv->GetServerName())
1461                         {
1462                                 chanrec *c = (chanrec*)dest;
1463                                 std::deque<std::string> params;
1464                                 params.push_back(c->name);
1465                                 params.push_back(":"+text);
1466                                 DoOneToMany(user->nick,"PRIVMSG",params);
1467                         }
1468                 }
1469         }
1470
1471         virtual void OnUserJoin(userrec* user, chanrec* channel)
1472         {
1473                 // Only do this for local users
1474                 if (std::string(user->server) == Srv->GetServerName())
1475                 {
1476                         log(DEBUG,"**** User on %s JOINS %s",user->server,channel->name);
1477                         std::deque<std::string> params;
1478                         params.clear();
1479                         params.push_back(channel->name);
1480                         if (*channel->key)
1481                         {
1482                                 log(DEBUG,"**** With key %s",channel->key);
1483                                 // if the channel has a key, force the join by emulating the key.
1484                                 params.push_back(channel->key);
1485                         }
1486                         DoOneToMany(user->nick,"JOIN",params);
1487                 }
1488         }
1489
1490         virtual void OnUserPart(userrec* user, chanrec* channel)
1491         {
1492                 if (std::string(user->server) == Srv->GetServerName())
1493                 {
1494                         log(DEBUG,"**** User on %s PARTS %s",user->server,channel->name);
1495                         std::deque<std::string> params;
1496                         params.clear();
1497                         params.push_back(channel->name);
1498                         DoOneToMany(user->nick,"PART",params);
1499                 }
1500         }
1501
1502         virtual void OnUserConnect(userrec* user)
1503         {
1504                 char agestr[MAXBUF];
1505                 if (std::string(user->server) == Srv->GetServerName())
1506                 {
1507                         log(DEBUG,"**** User on %s CONNECTS: %s",user->server,user->nick);
1508                         std::deque<std::string> params;
1509                         snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
1510                         params.clear();
1511                         params.push_back(agestr);
1512                         params.push_back(user->nick);
1513                         params.push_back(user->host);
1514                         params.push_back(user->dhost);
1515                         params.push_back(user->ident);
1516                         params.push_back("+"+std::string(user->modes));
1517                         params.push_back(user->ip);
1518                         params.push_back(":"+std::string(user->fullname));
1519                         DoOneToMany(Srv->GetServerName(),"NICK",params);
1520                 }
1521         }
1522
1523         virtual void OnUserQuit(userrec* user, std::string reason)
1524         {
1525                 if (std::string(user->server) == Srv->GetServerName())
1526                 {
1527                         log(DEBUG,"**** User on %s QUITS: %s",user->server,user->nick);
1528                         std::deque<std::string> params;
1529                         params.push_back(":"+reason);
1530                         DoOneToMany(user->nick,"QUIT",params);
1531                 }
1532         }
1533
1534         virtual void OnUserPostNick(userrec* user, std::string oldnick)
1535         {
1536                 if (std::string(user->server) == Srv->GetServerName())
1537                 {
1538                         log(DEBUG,"**** User on %s changes NICK: %s",user->server,user->nick);
1539                         std::deque<std::string> params;
1540                         params.push_back(user->nick);
1541                         DoOneToMany(oldnick,"NICK",params);
1542                 }
1543         }
1544
1545         virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
1546         {
1547                 if (std::string(source->server) == Srv->GetServerName())
1548                 {
1549                         log(DEBUG,"**** User on %s KICKs: %s %s",source->server,source->nick,user->nick);
1550                         std::deque<std::string> params;
1551                         params.push_back(chan->name);
1552                         params.push_back(user->nick);
1553                         params.push_back(":"+reason);
1554                         DoOneToMany(source->nick,"KICK",params);
1555                 }
1556         }
1557
1558         virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
1559         {
1560                 std::deque<std::string> params;
1561                 params.push_back(dest->nick);
1562                 params.push_back(":"+reason);
1563                 DoOneToMany(source->nick,"KILL",params);
1564         }
1565
1566         // note: the protocol does not allow direct umode +o except
1567         // via NICK with 8 params. sending OPERTYPE infers +o modechange
1568         // locally.
1569         virtual void OnOper(userrec* user, std::string opertype)
1570         {
1571                 if (std::string(user->server) == Srv->GetServerName())
1572                 {
1573                         std::deque<std::string> params;
1574                         params.push_back(opertype);
1575                         DoOneToMany(user->nick,"OPERTYPE",params);
1576                 }
1577         }
1578
1579         virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
1580         {
1581                 log(DEBUG,"*** ONMODE TRIGGER");
1582                 if (std::string(user->server) == Srv->GetServerName())
1583                 {
1584                         log(DEBUG,"*** LOCAL");
1585                         if (target_type == TYPE_USER)
1586                         {
1587                                 userrec* u = (userrec*)dest;
1588                                 std::deque<std::string> params;
1589                                 params.push_back(u->nick);
1590                                 params.push_back(text);
1591                                 DoOneToMany(user->nick,"MODE",params);
1592                         }
1593                         else
1594                         {
1595                                 chanrec* c = (chanrec*)dest;
1596                                 std::deque<std::string> params;
1597                                 params.push_back(c->name);
1598                                 params.push_back(text);
1599                                 DoOneToMany(user->nick,"MODE",params);
1600                         }
1601                 }
1602         }
1603
1604         virtual ~ModuleSpanningTree()
1605         {
1606                 delete Srv;
1607         }
1608
1609         virtual Version GetVersion()
1610         {
1611                 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
1612         }
1613 };
1614
1615
1616 class ModuleSpanningTreeFactory : public ModuleFactory
1617 {
1618  public:
1619         ModuleSpanningTreeFactory()
1620         {
1621         }
1622         
1623         ~ModuleSpanningTreeFactory()
1624         {
1625         }
1626         
1627         virtual Module * CreateModule()
1628         {
1629                 return new ModuleSpanningTree;
1630         }
1631         
1632 };
1633
1634
1635 extern "C" void * init_module( void )
1636 {
1637         return new ModuleSpanningTreeFactory;
1638 }
1639