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