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