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