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