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