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