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