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