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