]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree.cpp
Using the wrong iterator
[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 std::deque<TreeServer*> GetListOfServersForChannel(chanrec* c)
1442 {
1443         std::deque<TreeServer*> list;
1444         std::vector<char*> *ulist = c->GetUsers();
1445         for (unsigned int i = 0; i < ulist->size(); 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.clear();
1474                                         par.push_back(params[0]);
1475                                         par.push_back(":"+params[1]);
1476                                         DoOneToOne(prefix,command,par,d->server);
1477                                         return true;
1478                                 }
1479                         }
1480                         else
1481                         {
1482                                 log(DEBUG,"Channel privmsg going to chan %s",params[0].c_str());
1483                                 chanrec* c = Srv->FindChannel(params[0]);
1484                                 if (c)
1485                                 {
1486                                         std::deque<TreeServer*> list = GetListOfServersForChannel(c);
1487                                         log(DEBUG,"Got a list of %d servers",list.size());
1488                                         for (unsigned int i = 0; i < list.size(); i++)
1489                                         {
1490                                                 TreeSocket* Sock = list[i]->GetSocket();
1491                                                 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
1492                                                 {
1493                                                         log(DEBUG,"Writing privmsg to server %s",list[i]->GetName().c_str());
1494                                                         Sock->WriteLine(data);
1495                                                 }
1496                                         }
1497                                         return true;
1498                                 }
1499                         }
1500                 }
1501         }
1502         for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1503         {
1504                 TreeServer* Route = TreeRoot->GetChild(x);
1505                 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1506                 {
1507                         TreeSocket* Sock = Route->GetSocket();
1508                         Sock->WriteLine(data);
1509                 }
1510         }
1511         return true;
1512 }
1513
1514 bool DoOneToAllButSender(std::string prefix, std::string command, std::deque<std::string> params, std::string omit)
1515 {
1516         TreeServer* omitroute = BestRouteTo(omit);
1517         std::string FullLine = ":" + prefix + " " + command;
1518         for (unsigned int x = 0; x < params.size(); x++)
1519         {
1520                 FullLine = FullLine + " " + params[x];
1521         }
1522         for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1523         {
1524                 TreeServer* Route = TreeRoot->GetChild(x);
1525                 // Send the line IF:
1526                 // The route has a socket (its a direct connection)
1527                 // The route isnt the one to be omitted
1528                 // The route isnt the path to the one to be omitted
1529                 if ((Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
1530                 {
1531                         TreeSocket* Sock = Route->GetSocket();
1532                         Sock->WriteLine(FullLine);
1533                 }
1534         }
1535         return true;
1536 }
1537
1538 bool DoOneToMany(std::string prefix, std::string command, std::deque<std::string> params)
1539 {
1540         std::string FullLine = ":" + prefix + " " + command;
1541         for (unsigned int x = 0; x < params.size(); x++)
1542         {
1543                 FullLine = FullLine + " " + params[x];
1544         }
1545         for (unsigned int x = 0; x < TreeRoot->ChildCount(); x++)
1546         {
1547                 TreeServer* Route = TreeRoot->GetChild(x);
1548                 if (Route->GetSocket())
1549                 {
1550                         TreeSocket* Sock = Route->GetSocket();
1551                         Sock->WriteLine(FullLine);
1552                 }
1553         }
1554         return true;
1555 }
1556
1557 bool DoOneToOne(std::string prefix, std::string command, std::deque<std::string> params, std::string target)
1558 {
1559         TreeServer* Route = BestRouteTo(target);
1560         if (Route)
1561         {
1562                 std::string FullLine = ":" + prefix + " " + command;
1563                 for (unsigned int x = 0; x < params.size(); x++)
1564                 {
1565                         FullLine = FullLine + " " + params[x];
1566                 }
1567                 if (Route->GetSocket())
1568                 {
1569                         TreeSocket* Sock = Route->GetSocket();
1570                         Sock->WriteLine(FullLine);
1571                 }
1572                 return true;
1573         }
1574         else
1575         {
1576                 return true;
1577         }
1578 }
1579
1580 std::vector<TreeSocket*> Bindings;
1581
1582 void ReadConfiguration(bool rebind)
1583 {
1584         if (rebind)
1585         {
1586                 for (int j =0; j < Conf->Enumerate("bind"); j++)
1587                 {
1588                         std::string Type = Conf->ReadValue("bind","type",j);
1589                         std::string IP = Conf->ReadValue("bind","address",j);
1590                         long Port = Conf->ReadInteger("bind","port",j,true);
1591                         if (Type == "servers")
1592                         {
1593                                 if (IP == "*")
1594                                 {
1595                                         IP = "";
1596                                 }
1597                                 TreeSocket* listener = new TreeSocket(IP.c_str(),Port,true,10);
1598                                 if (listener->GetState() == I_LISTENING)
1599                                 {
1600                                         Srv->AddSocket(listener);
1601                                         Bindings.push_back(listener);
1602                                 }
1603                                 else
1604                                 {
1605                                         log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %d",Port);
1606                                         listener->Close();
1607                                         delete listener;
1608                                 }
1609                         }
1610                 }
1611         }
1612         LinkBlocks.clear();
1613         for (int j =0; j < Conf->Enumerate("link"); j++)
1614         {
1615                 Link L;
1616                 L.Name = Conf->ReadValue("link","name",j);
1617                 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
1618                 L.Port = Conf->ReadInteger("link","port",j,true);
1619                 L.SendPass = Conf->ReadValue("link","sendpass",j);
1620                 L.RecvPass = Conf->ReadValue("link","recvpass",j);
1621                 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
1622                 L.NextConnectTime = time(NULL) + L.AutoConnect;
1623                 LinkBlocks.push_back(L);
1624                 log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
1625         }
1626 }
1627
1628
1629 class ModuleSpanningTree : public Module
1630 {
1631         std::vector<TreeSocket*> Bindings;
1632         int line;
1633         int NumServers;
1634
1635  public:
1636
1637         ModuleSpanningTree()
1638         {
1639                 Srv = new Server;
1640                 Conf = new ConfigReader;
1641                 Bindings.clear();
1642
1643                 // Create the root of the tree
1644                 TreeRoot = new TreeServer(Srv->GetServerName(),Srv->GetServerDescription());
1645
1646                 ReadConfiguration(true);
1647         }
1648
1649         void ShowLinks(TreeServer* Current, userrec* user, int hops)
1650         {
1651                 std::string Parent = TreeRoot->GetName();
1652                 if (Current->GetParent())
1653                 {
1654                         Parent = Current->GetParent()->GetName();
1655                 }
1656                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1657                 {
1658                         ShowLinks(Current->GetChild(q),user,hops+1);
1659                 }
1660                 WriteServ(user->fd,"364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),Parent.c_str(),hops,Current->GetDesc().c_str());
1661         }
1662
1663         int CountLocalServs()
1664         {
1665                 return TreeRoot->ChildCount();
1666         }
1667
1668         void CountServsRecursive(TreeServer* Current)
1669         {
1670                 NumServers++;
1671                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1672                 {
1673                         CountServsRecursive(Current->GetChild(q));
1674                 }
1675         }
1676         
1677         int CountServs()
1678         {
1679                 NumServers = 0;
1680                 CountServsRecursive(TreeRoot);
1681                 return NumServers;
1682         }
1683
1684         void HandleLinks(char** parameters, int pcnt, userrec* user)
1685         {
1686                 ShowLinks(TreeRoot,user,0);
1687                 WriteServ(user->fd,"365 %s * :End of /LINKS list.",user->nick);
1688                 return;
1689         }
1690
1691         void HandleLusers(char** parameters, int pcnt, userrec* user)
1692         {
1693                 WriteServ(user->fd,"251 %s :There are %d users and %d invisible on %d servers",user->nick,usercnt()-usercount_invisible(),usercount_invisible(),this->CountServs());
1694                 WriteServ(user->fd,"252 %s %d :operator(s) online",user->nick,usercount_opers());
1695                 WriteServ(user->fd,"253 %s %d :unknown connections",user->nick,usercount_unknown());
1696                 WriteServ(user->fd,"254 %s %d :channels formed",user->nick,chancount());
1697                 WriteServ(user->fd,"254 %s :I have %d clients and %d servers",user->nick,local_count(),this->CountLocalServs());
1698                 return;
1699         }
1700
1701         // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
1702
1703         void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80])
1704         {
1705                 if (line < 128)
1706                 {
1707                         for (int t = 0; t < depth; t++)
1708                         {
1709                                 matrix[line][t] = ' ';
1710                         }
1711                         strlcpy(&matrix[line][depth],Current->GetName().c_str(),80);
1712                         line++;
1713                         for (unsigned int q = 0; q < Current->ChildCount(); q++)
1714                         {
1715                                 ShowMap(Current->GetChild(q),user,depth+2,matrix);
1716                         }
1717                 }
1718         }
1719
1720         // Ok, prepare to be confused.
1721         // After much mulling over how to approach this, it struck me that
1722         // the 'usual' way of doing a /MAP isnt the best way. Instead of
1723         // keeping track of a ton of ascii characters, and line by line
1724         // under recursion working out where to place them using multiplications
1725         // and divisons, we instead render the map onto a backplane of characters
1726         // (a character matrix), then draw the branches as a series of "L" shapes
1727         // from the nodes. This is not only friendlier on CPU it uses less stack.
1728
1729         void HandleMap(char** parameters, int pcnt, userrec* user)
1730         {
1731                 // This array represents a virtual screen which we will
1732                 // "scratch" draw to, as the console device of an irc
1733                 // client does not provide for a proper terminal.
1734                 char matrix[128][80];
1735                 for (unsigned int t = 0; t < 128; t++)
1736                 {
1737                         matrix[t][0] = '\0';
1738                 }
1739                 line = 0;
1740                 // The only recursive bit is called here.
1741                 ShowMap(TreeRoot,user,0,matrix);
1742                 // Process each line one by one. The algorithm has a limit of
1743                 // 128 servers (which is far more than a spanning tree should have
1744                 // anyway, so we're ok). This limit can be raised simply by making
1745                 // the character matrix deeper, 128 rows taking 10k of memory.
1746                 for (int l = 1; l < line; l++)
1747                 {
1748                         // scan across the line looking for the start of the
1749                         // servername (the recursive part of the algorithm has placed
1750                         // the servers at indented positions depending on what they
1751                         // are related to)
1752                         int first_nonspace = 0;
1753                         while (matrix[l][first_nonspace] == ' ')
1754                         {
1755                                 first_nonspace++;
1756                         }
1757                         first_nonspace--;
1758                         // Draw the `- (corner) section: this may be overwritten by
1759                         // another L shape passing along the same vertical pane, becoming
1760                         // a |- (branch) section instead.
1761                         matrix[l][first_nonspace] = '-';
1762                         matrix[l][first_nonspace-1] = '`';
1763                         int l2 = l - 1;
1764                         // Draw upwards until we hit the parent server, causing possibly
1765                         // other corners (`-) to become branches (|-)
1766                         while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
1767                         {
1768                                 matrix[l2][first_nonspace-1] = '|';
1769                                 l2--;
1770                         }
1771                 }
1772                 // dump the whole lot to the user. This is the easy bit, honest.
1773                 for (int t = 0; t < line; t++)
1774                 {
1775                         WriteServ(user->fd,"006 %s :%s",user->nick,&matrix[t][0]);
1776                 }
1777                 WriteServ(user->fd,"007 %s :End of /MAP",user->nick);
1778                 return;
1779         }
1780
1781         int HandleSquit(char** parameters, int pcnt, userrec* user)
1782         {
1783                 TreeServer* s = FindServerMask(parameters[0]);
1784                 if (s)
1785                 {
1786                         TreeSocket* sock = s->GetSocket();
1787                         if (sock)
1788                         {
1789                                 WriteOpers("*** SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
1790                                 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
1791                                 sock->Close();
1792                         }
1793                         else
1794                         {
1795                                 WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
1796                         }
1797                 }
1798                 else
1799                 {
1800                          WriteServ(user->fd,"NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
1801                 }
1802                 return 1;
1803         }
1804
1805         void DoPingChecks(time_t curtime)
1806         {
1807                 for (unsigned int j = 0; j < TreeRoot->ChildCount(); j++)
1808                 {
1809                         TreeServer* serv = TreeRoot->GetChild(j);
1810                         TreeSocket* sock = serv->GetSocket();
1811                         if (sock)
1812                         {
1813                                 if (curtime >= serv->NextPingTime())
1814                                 {
1815                                         if (serv->AnsweredLastPing())
1816                                         {
1817                                                 sock->WriteLine(":"+Srv->GetServerName()+" PING "+serv->GetName());
1818                                                 serv->SetNextPingTime(curtime + 60);
1819                                         }
1820                                         else
1821                                         {
1822                                                 // they didnt answer, boot them
1823                                                 WriteOpers("*** Server \002%s\002 pinged out",serv->GetName().c_str());
1824                                                 sock->Squit(serv,"Ping timeout");
1825                                                 sock->Close();
1826                                                 return;
1827                                         }
1828                                 }
1829                         }
1830                 }
1831         }
1832
1833         void AutoConnectServers(time_t curtime)
1834         {
1835                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1836                 {
1837                         if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
1838                         {
1839                                 log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
1840                                 x->NextConnectTime = curtime + x->AutoConnect;
1841                                 TreeServer* CheckDupe = FindServer(x->Name);
1842                                 if (!CheckDupe)
1843                                 {
1844                                         // an autoconnected server is not connected. Check if its time to connect it
1845                                         WriteOpers("*** AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
1846                                         TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1847                                         Srv->AddSocket(newsocket);
1848                                 }
1849                         }
1850                 }
1851         }
1852
1853         int HandleVersion(char** parameters, int pcnt, userrec* user)
1854         {
1855                 // we've already checked if pcnt > 0, so this is safe
1856                 TreeServer* found = FindServerMask(parameters[0]);
1857                 if (found)
1858                 {
1859                         std::string Version = found->GetVersion();
1860                         WriteServ(user->fd,"351 %s :%s",user->nick,Version.c_str());
1861                 }
1862                 else
1863                 {
1864                         WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
1865                 }
1866                 return 1;
1867         }
1868         
1869         int HandleConnect(char** parameters, int pcnt, userrec* user)
1870         {
1871                 for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
1872                 {
1873                         if (Srv->MatchText(x->Name.c_str(),parameters[0]))
1874                         {
1875                                 TreeServer* CheckDupe = FindServer(x->Name);
1876                                 if (!CheckDupe)
1877                                 {
1878                                         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);
1879                                         TreeSocket* newsocket = new TreeSocket(x->IPAddr,x->Port,false,10,x->Name);
1880                                         Srv->AddSocket(newsocket);
1881                                         return 1;
1882                                 }
1883                                 else
1884                                 {
1885                                         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());
1886                                         return 1;
1887                                 }
1888                         }
1889                 }
1890                 WriteServ(user->fd,"NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
1891                 return 1;
1892         }
1893
1894         virtual int OnPreCommand(std::string command, char **parameters, int pcnt, userrec *user)
1895         {
1896                 if (command == "CONNECT")
1897                 {
1898                         return this->HandleConnect(parameters,pcnt,user);
1899                 }
1900                 else if (command == "SQUIT")
1901                 {
1902                         return this->HandleSquit(parameters,pcnt,user);
1903                 }
1904                 else if (command == "MAP")
1905                 {
1906                         this->HandleMap(parameters,pcnt,user);
1907                         return 1;
1908                 }
1909                 else if (command == "LUSERS")
1910                 {
1911                         this->HandleLusers(parameters,pcnt,user);
1912                         return 1;
1913                 }
1914                 else if (command == "LINKS")
1915                 {
1916                         this->HandleLinks(parameters,pcnt,user);
1917                         return 1;
1918                 }
1919                 else if ((command == "VERSION") && (pcnt > 0))
1920                 {
1921                         this->HandleVersion(parameters,pcnt,user);
1922                         return 1;
1923                 }
1924                 else if (Srv->IsValidModuleCommand(command, pcnt, user))
1925                 {
1926                         // this bit of code cleverly routes all module commands
1927                         // to all remote severs *automatically* so that modules
1928                         // can just handle commands locally, without having
1929                         // to have any special provision in place for remote
1930                         // commands and linking protocols.
1931                         std::deque<std::string> params;
1932                         params.clear();
1933                         for (int j = 0; j < pcnt; j++)
1934                         {
1935                                 if (strchr(parameters[j],' '))
1936                                 {
1937                                         params.push_back(":" + std::string(parameters[j]));
1938                                 }
1939                                 else
1940                                 {
1941                                         params.push_back(std::string(parameters[j]));
1942                                 }
1943                         }
1944                         DoOneToMany(user->nick,command,params);
1945                 }
1946                 return 0;
1947         }
1948
1949         virtual void OnGetServerDescription(std::string servername,std::string &description)
1950         {
1951                 TreeServer* s = FindServer(servername);
1952                 if (s)
1953                 {
1954                         description = s->GetDesc();
1955                 }
1956         }
1957
1958         virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
1959         {
1960                 if (std::string(source->server) == Srv->GetServerName())
1961                 {
1962                         std::deque<std::string> params;
1963                         params.push_back(dest->nick);
1964                         params.push_back(channel->name);
1965                         DoOneToMany(source->nick,"INVITE",params);
1966                 }
1967         }
1968
1969         virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, std::string topic)
1970         {
1971                 std::deque<std::string> params;
1972                 params.push_back(chan->name);
1973                 params.push_back(":"+topic);
1974                 DoOneToMany(user->nick,"TOPIC",params);
1975         }
1976
1977         virtual void OnWallops(userrec* user, std::string text)
1978         {
1979                 if (std::string(user->server) == Srv->GetServerName())
1980                 {
1981                         std::deque<std::string> params;
1982                         params.push_back(":"+text);
1983                         DoOneToMany(user->nick,"WALLOPS",params);
1984                 }
1985         }
1986
1987         virtual void OnUserNotice(userrec* user, void* dest, int target_type, std::string text)
1988         {
1989                 if (target_type == TYPE_USER)
1990                 {
1991                         userrec* d = (userrec*)dest;
1992                         if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
1993                         {
1994                                 std::deque<std::string> params;
1995                                 params.clear();
1996                                 params.push_back(d->nick);
1997                                 params.push_back(":"+text);
1998                                 DoOneToOne(user->nick,"NOTICE",params,d->server);
1999                         }
2000                 }
2001                 else
2002                 {
2003                         if (std::string(user->server) == Srv->GetServerName())
2004                         {
2005                                 chanrec *c = (chanrec*)dest;
2006                                 std::deque<TreeServer*> list = GetListOfServersForChannel(c);
2007                                 for (unsigned int i = 0; i < list.size(); i++)
2008                                 {
2009                                         TreeSocket* Sock = list[i]->GetSocket();
2010                                         if (Sock)
2011                                                 Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+std::string(c->name)+" :"+text);
2012                                 }
2013                         }
2014                 }
2015         }
2016
2017         virtual void OnUserMessage(userrec* user, void* dest, int target_type, std::string text)
2018         {
2019                 if (target_type == TYPE_USER)
2020                 {
2021                         // route private messages which are targetted at clients only to the server
2022                         // which needs to receive them
2023                         userrec* d = (userrec*)dest;
2024                         if ((std::string(d->server) != Srv->GetServerName()) && (std::string(user->server) == Srv->GetServerName()))
2025                         {
2026                                 std::deque<std::string> params;
2027                                 params.clear();
2028                                 params.push_back(d->nick);
2029                                 params.push_back(":"+text);
2030                                 DoOneToOne(user->nick,"PRIVMSG",params,d->server);
2031                         }
2032                 }
2033                 else
2034                 {
2035                         if (std::string(user->server) == Srv->GetServerName())
2036                         {
2037                                 chanrec *c = (chanrec*)dest;
2038                                 std::deque<TreeServer*> list = GetListOfServersForChannel(c);
2039                                 for (unsigned int i = 0; i < list.size(); i++)
2040                                 {
2041                                         TreeSocket* Sock = list[i]->GetSocket();
2042                                         if (Sock)
2043                                                 Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+std::string(c->name)+" :"+text);
2044                                 }
2045                         }
2046                 }
2047         }
2048
2049         virtual void OnBackgroundTimer(time_t curtime)
2050         {
2051                 AutoConnectServers(curtime);
2052                 DoPingChecks(curtime);
2053         }
2054
2055         virtual void OnUserJoin(userrec* user, chanrec* channel)
2056         {
2057                 // Only do this for local users
2058                 if (std::string(user->server) == Srv->GetServerName())
2059                 {
2060                         std::deque<std::string> params;
2061                         params.clear();
2062                         params.push_back(channel->name);
2063                         if (*channel->key)
2064                         {
2065                                 // if the channel has a key, force the join by emulating the key.
2066                                 params.push_back(channel->key);
2067                         }
2068                         if (channel->GetUserCounter() > 1)
2069                         {
2070                                 // not the first in the channel
2071                                 DoOneToMany(user->nick,"JOIN",params);
2072                         }
2073                         else
2074                         {
2075                                 // first in the channel, set up their permissions
2076                                 // and the channel TS with FJOIN.
2077                                 char ts[24];
2078                                 snprintf(ts,24,"%lu",(unsigned long)channel->age);
2079                                 params.clear();
2080                                 params.push_back(channel->name);
2081                                 params.push_back(ts);
2082                                 params.push_back("@"+std::string(user->nick));
2083                                 DoOneToMany(Srv->GetServerName(),"FJOIN",params);
2084                         }
2085                 }
2086         }
2087
2088         virtual void OnChangeHost(userrec* user, std::string newhost)
2089         {
2090                 // only occurs for local clients
2091                 std::deque<std::string> params;
2092                 params.push_back(newhost);
2093                 DoOneToMany(user->nick,"FHOST",params);
2094         }
2095
2096         virtual void OnChangeName(userrec* user, std::string gecos)
2097         {
2098                 // only occurs for local clients
2099                 std::deque<std::string> params;
2100                 params.push_back(gecos);
2101                 DoOneToMany(user->nick,"FNAME",params);
2102         }
2103
2104         virtual void OnUserPart(userrec* user, chanrec* channel)
2105         {
2106                 if (std::string(user->server) == Srv->GetServerName())
2107                 {
2108                         std::deque<std::string> params;
2109                         params.clear();
2110                         params.push_back(channel->name);
2111                         DoOneToMany(user->nick,"PART",params);
2112                 }
2113         }
2114
2115         virtual void OnUserConnect(userrec* user)
2116         {
2117                 char agestr[MAXBUF];
2118                 if (std::string(user->server) == Srv->GetServerName())
2119                 {
2120                         std::deque<std::string> params;
2121                         snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
2122                         params.clear();
2123                         params.push_back(agestr);
2124                         params.push_back(user->nick);
2125                         params.push_back(user->host);
2126                         params.push_back(user->dhost);
2127                         params.push_back(user->ident);
2128                         params.push_back("+"+std::string(user->modes));
2129                         params.push_back(user->ip);
2130                         params.push_back(":"+std::string(user->fullname));
2131                         DoOneToMany(Srv->GetServerName(),"NICK",params);
2132                 }
2133         }
2134
2135         virtual void OnUserQuit(userrec* user, std::string reason)
2136         {
2137                 if (std::string(user->server) == Srv->GetServerName())
2138                 {
2139                         std::deque<std::string> params;
2140                         params.push_back(":"+reason);
2141                         DoOneToMany(user->nick,"QUIT",params);
2142                 }
2143         }
2144
2145         virtual void OnUserPostNick(userrec* user, std::string oldnick)
2146         {
2147                 if (std::string(user->server) == Srv->GetServerName())
2148                 {
2149                         std::deque<std::string> params;
2150                         params.push_back(user->nick);
2151                         DoOneToMany(oldnick,"NICK",params);
2152                 }
2153         }
2154
2155         virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, std::string reason)
2156         {
2157                 if (std::string(source->server) == Srv->GetServerName())
2158                 {
2159                         std::deque<std::string> params;
2160                         params.push_back(chan->name);
2161                         params.push_back(user->nick);
2162                         params.push_back(":"+reason);
2163                         DoOneToMany(source->nick,"KICK",params);
2164                 }
2165         }
2166
2167         virtual void OnRemoteKill(userrec* source, userrec* dest, std::string reason)
2168         {
2169                 std::deque<std::string> params;
2170                 params.push_back(dest->nick);
2171                 params.push_back(":"+reason);
2172                 DoOneToMany(source->nick,"KILL",params);
2173         }
2174
2175         virtual void OnRehash(std::string parameter)
2176         {
2177                 if (parameter != "")
2178                 {
2179                         std::deque<std::string> params;
2180                         params.push_back(parameter);
2181                         DoOneToMany(Srv->GetServerName(),"REHASH",params);
2182                         // check for self
2183                         if (Srv->MatchText(Srv->GetServerName(),parameter))
2184                         {
2185                                 Srv->SendOpers("*** Remote rehash initiated from server \002"+Srv->GetServerName()+"\002.");
2186                                 Srv->RehashServer();
2187                         }
2188                 }
2189                 ReadConfiguration(false);
2190         }
2191
2192         // note: the protocol does not allow direct umode +o except
2193         // via NICK with 8 params. sending OPERTYPE infers +o modechange
2194         // locally.
2195         virtual void OnOper(userrec* user, std::string opertype)
2196         {
2197                 if (std::string(user->server) == Srv->GetServerName())
2198                 {
2199                         std::deque<std::string> params;
2200                         params.push_back(opertype);
2201                         DoOneToMany(user->nick,"OPERTYPE",params);
2202                 }
2203         }
2204
2205         virtual void OnMode(userrec* user, void* dest, int target_type, std::string text)
2206         {
2207                 if (std::string(user->server) == Srv->GetServerName())
2208                 {
2209                         if (target_type == TYPE_USER)
2210                         {
2211                                 userrec* u = (userrec*)dest;
2212                                 std::deque<std::string> params;
2213                                 params.push_back(u->nick);
2214                                 params.push_back(text);
2215                                 DoOneToMany(user->nick,"MODE",params);
2216                         }
2217                         else
2218                         {
2219                                 chanrec* c = (chanrec*)dest;
2220                                 std::deque<std::string> params;
2221                                 params.push_back(c->name);
2222                                 params.push_back(text);
2223                                 DoOneToMany(user->nick,"MODE",params);
2224                         }
2225                 }
2226         }
2227
2228         virtual void ProtoSendMode(void* opaque, int target_type, void* target, std::string modeline)
2229         {
2230                 TreeSocket* s = (TreeSocket*)opaque;
2231                 if (target)
2232                 {
2233                         if (target_type == TYPE_USER)
2234                         {
2235                                 userrec* u = (userrec*)target;
2236                                 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+u->nick+" "+modeline);
2237                         }
2238                         else
2239                         {
2240                                 chanrec* c = (chanrec*)target;
2241                                 s->WriteLine(":"+Srv->GetServerName()+" FMODE "+c->name+" "+modeline);
2242                         }
2243                 }
2244         }
2245
2246         virtual ~ModuleSpanningTree()
2247         {
2248                 delete Srv;
2249         }
2250
2251         virtual Version GetVersion()
2252         {
2253                 return Version(1,0,0,0,VF_STATIC|VF_VENDOR);
2254         }
2255 };
2256
2257
2258 class ModuleSpanningTreeFactory : public ModuleFactory
2259 {
2260  public:
2261         ModuleSpanningTreeFactory()
2262         {
2263         }
2264         
2265         ~ModuleSpanningTreeFactory()
2266         {
2267         }
2268         
2269         virtual Module * CreateModule()
2270         {
2271                 TreeProtocolModule = new ModuleSpanningTree;
2272                 return TreeProtocolModule;
2273         }
2274         
2275 };
2276
2277
2278 extern "C" void * init_module( void )
2279 {
2280         return new ModuleSpanningTreeFactory;
2281 }