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