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