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