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