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