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