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