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