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