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