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