]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree.cpp
Protocl-Version bump to 1102
[user/henk/code/inspircd.git] / src / modules / m_spanningtree.cpp
1 /*   +------------------------------------+
2  *   | Inspire Internet Relay Chat Daemon |
3  *   +------------------------------------+
4  *
5  *  InspIRCd is copyright (C) 2002-2006 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 #include "configreader.h"
20 #include "users.h"
21 #include "channels.h"
22 #include "modules.h"
23 #include "commands/cmd_whois.h"
24 #include "commands/cmd_stats.h"
25 #include "socket.h"
26 #include "inspircd.h"
27 #include "wildcard.h"
28 #include "xline.h"
29 #include "aes.h"
30
31 /** If you make a change which breaks the protocol, increment this.
32  * If you  completely change the protocol, completely change the number.
33  */
34 const long ProtocolVersion = 1102;
35
36 /*
37  * The server list in InspIRCd is maintained as two structures
38  * which hold the data in different ways. Most of the time, we
39  * want to very quicky obtain three pieces of information:
40  *
41  * (1) The information on a server
42  * (2) The information on the server we must send data through
43  *     to actually REACH the server we're after
44  * (3) Potentially, the child/parent objects of this server
45  *
46  * The InspIRCd spanning protocol provides easy access to these
47  * by storing the data firstly in a recursive structure, where
48  * each item references its parent item, and a dynamic list
49  * of child items, and another structure which stores the items
50  * hashed, linearly. This means that if we want to find a server
51  * by name quickly, we can look it up in the hash, avoiding
52  * any O(n) lookups. If however, during a split or sync, we want
53  * to apply an operation to a server, and any of its child objects
54  * we can resort to recursion to walk the tree structure.
55  * Any socket can have one of five states at any one time.
56  * The LISTENER state indicates a socket which is listening
57  * for connections. It cannot receive data itself, only incoming
58  * sockets.
59  * The CONNECTING state indicates an outbound socket which is
60  * waiting to be writeable.
61  * The WAIT_AUTH_1 state indicates the socket is outbound and
62  * has successfully connected, but has not yet sent and received
63  * SERVER strings.
64  * The WAIT_AUTH_2 state indicates that the socket is inbound
65  * (allocated by a LISTENER) but has not yet sent and received
66  * SERVER strings.
67  * The CONNECTED state represents a fully authorized, fully
68  * connected server.
69  */
70 enum ServerState { LISTENER, CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED };
71
72 /* Foward declarations */
73 class TreeServer;
74 class TreeSocket;
75 class Link;
76 class ModuleSpanningTree;
77
78 /* This hash_map holds the hash equivalent of the server
79  * tree, used for rapid linear lookups.
80  */
81 typedef nspace::hash_map<std::string, TreeServer*, nspace::hash<string>, irc::StrHashComp> server_hash;
82
83
84 /** The Link class might as well be a struct,
85  * but this is C++ and we don't believe in structs (!).
86  * It holds the entire information of one <link>
87  * tag from the main config file. We maintain a list
88  * of them, and populate the list on rehash/load.
89  */
90 class Link : public classbase
91 {
92  public:
93         irc::string Name;
94         std::string IPAddr;
95         int Port;
96         std::string SendPass;
97         std::string RecvPass;
98         unsigned long AutoConnect;
99         time_t NextConnectTime;
100         std::string EncryptionKey;
101         bool HiddenFromStats;
102         std::string FailOver;
103         int Timeout;
104 };
105
106 /** Contains helper functions and variables for this module,
107  * and keeps them out of the global namespace
108  */
109 class SpanningTreeUtilities
110 {
111  private:
112         /** Creator server
113          */
114         InspIRCd* ServerInstance;
115  public:
116         /** Creator module
117          */
118         ModuleSpanningTree* Creator;
119         /** Flatten links and /MAP for non-opers
120          */
121         bool FlatLinks;
122         /** Hide U-Lined servers in /MAP and /LINKS
123          */
124         bool HideULines;
125         /** Announce TS changes to channels on merge
126          */
127         bool AnnounceTSChange;
128         /** Synchronize timestamps between servers
129          */
130         bool EnableTimeSync;
131         /** Socket bindings for listening sockets
132          */
133         std::vector<TreeSocket*> Bindings;
134         /** This variable represents the root of the server tree
135          */
136         TreeServer *TreeRoot;
137         /** IPs allowed to link to us
138          */
139         std::vector<std::string> ValidIPs;
140         /** Hash of currently connected servers by name
141          */
142         server_hash serverlist;
143         /** Holds the data from the <link> tags in the conf
144          */
145         std::vector<Link> LinkBlocks;
146
147         /** Initialise utility class
148          */
149         SpanningTreeUtilities(InspIRCd* Instance, ModuleSpanningTree* Creator);
150         /** Destroy class and free listeners etc
151          */
152         ~SpanningTreeUtilities();
153         /** Send a message from this server to one other local or remote
154          */
155         bool DoOneToOne(const std::string &prefix, const std::string &command, std::deque<std::string> &params, std::string target);
156         /** Send a message from this server to all but one other, local or remote
157          */
158         bool DoOneToAllButSender(const std::string &prefix, const std::string &command, std::deque<std::string> &params, std::string omit);
159         /** Send a message from this server to all but one other, local or remote
160          */
161         bool DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> &params, std::string omit);
162         /** Send a message from this server to all others
163          */
164         bool DoOneToMany(const std::string &prefix, const std::string &command, std::deque<std::string> &params);
165         /** Send a message from this server to all others
166          */
167         bool DoOneToMany(const char* prefix, const char* command, std::deque<std::string> &params);
168         /** Send a message from this server to all others, without doing any processing on the command (e.g. send it as-is with colons and all)
169          */
170         bool DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, std::deque<std::string> &params);
171         /** Read the spanningtree module's tags from the config file
172          */
173         void ReadConfiguration(bool rebind);
174         /** Add a server to the server list for GetListOfServersForChannel
175          */
176         void AddThisServer(TreeServer* server, std::deque<TreeServer*> &list);
177         /** Compile a list of servers which contain members of channel c
178          */
179         void GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list);
180         /** Find a server by name
181          */
182         TreeServer* FindServer(const std::string &ServerName);
183         /** Find a route to a server by name
184          */
185         TreeServer* BestRouteTo(const std::string &ServerName);
186         /** Find a server by glob mask
187          */
188         TreeServer* FindServerMask(const std::string &ServerName);
189         /** Returns true if this is a server name we recognise
190          */
191         bool IsServer(const std::string &ServerName);
192         /** Attempt to connect to the failover link of link x
193          */
194         void DoFailOver(Link* x);
195         /** Find a link tag from a server name
196          */
197         Link* FindLink(const std::string& name);
198 };
199
200
201 /** Each server in the tree is represented by one class of
202  * type TreeServer. A locally connected TreeServer can
203  * have a class of type TreeSocket associated with it, for
204  * remote servers, the TreeSocket entry will be NULL.
205  * Each server also maintains a pointer to its parent
206  * (NULL if this server is ours, at the top of the tree)
207  * and a pointer to its "Route" (see the comments in the
208  * constructors below), and also a dynamic list of pointers
209  * to its children which can be iterated recursively
210  * if required. Creating or deleting objects of type
211  i* TreeServer automatically maintains the hash_map of
212  * TreeServer items, deleting and inserting them as they
213  * are created and destroyed.
214  */
215 class TreeServer : public classbase
216 {
217         InspIRCd* ServerInstance;               /* Creator */
218         TreeServer* Parent;                     /* Parent entry */
219         TreeServer* Route;                      /* Route entry */
220         std::vector<TreeServer*> Children;      /* List of child objects */
221         irc::string ServerName;                 /* Server's name */
222         std::string ServerDesc;                 /* Server's description */
223         std::string VersionString;              /* Version string or empty string */
224         int UserCount;                          /* Not used in this version */
225         int OperCount;                          /* Not used in this version */
226         TreeSocket* Socket;                     /* For directly connected servers this points at the socket object */
227         time_t NextPing;                        /* After this time, the server should be PINGed*/
228         bool LastPingWasGood;                   /* True if the server responded to the last PING with a PONG */
229         SpanningTreeUtilities* Utils;           /* Utility class */
230         
231  public:
232
233         /** We don't use this constructor. Its a dummy, and won't cause any insertion
234          * of the TreeServer into the hash_map. See below for the two we DO use.
235          */
236         TreeServer(SpanningTreeUtilities* Util, InspIRCd* Instance) : ServerInstance(Instance), Utils(Util)
237         {
238                 Parent = NULL;
239                 ServerName = "";
240                 ServerDesc = "";
241                 VersionString = "";
242                 UserCount = OperCount = 0;
243                 VersionString = ServerInstance->GetVersionString();
244         }
245
246         /** We use this constructor only to create the 'root' item, Utils->TreeRoot, which
247          * represents our own server. Therefore, it has no route, no parent, and
248          * no socket associated with it. Its version string is our own local version.
249          */
250         TreeServer(SpanningTreeUtilities* Util, InspIRCd* Instance, std::string Name, std::string Desc) : ServerInstance(Instance), ServerName(Name.c_str()), ServerDesc(Desc), Utils(Util)
251         {
252                 Parent = NULL;
253                 VersionString = "";
254                 UserCount = ServerInstance->UserCount();
255                 OperCount = ServerInstance->OperCount();
256                 VersionString = ServerInstance->GetVersionString();
257                 Route = NULL;
258                 Socket = NULL; /* Fix by brain */
259                 AddHashEntry();
260         }
261
262         /** When we create a new server, we call this constructor to initialize it.
263          * This constructor initializes the server's Route and Parent, and sets up
264          * its ping counters so that it will be pinged one minute from now.
265          */
266         TreeServer(SpanningTreeUtilities* Util, InspIRCd* Instance, std::string Name, std::string Desc, TreeServer* Above, TreeSocket* Sock)
267                 : ServerInstance(Instance), Parent(Above), ServerName(Name.c_str()), ServerDesc(Desc), Socket(Sock), Utils(Util)
268         {
269                 VersionString = "";
270                 UserCount = OperCount = 0;
271                 this->SetNextPingTime(time(NULL) + 60);
272                 this->SetPingFlag();
273
274                 /* find the 'route' for this server (e.g. the one directly connected
275                  * to the local server, which we can use to reach it)
276                  *
277                  * In the following example, consider we have just added a TreeServer
278                  * class for server G on our network, of which we are server A.
279                  * To route traffic to G (marked with a *) we must send the data to
280                  * B (marked with a +) so this algorithm initializes the 'Route'
281                  * value to point at whichever server traffic must be routed through
282                  * to get here. If we were to try this algorithm with server B,
283                  * the Route pointer would point at its own object ('this').
284                  *
285                  *              A
286                  *             / \
287                  *          + B   C
288                  *           / \   \
289                  *          D   E   F
290                  *         /         \
291                  *      * G           H
292                  *
293                  * We only run this algorithm when a server is created, as
294                  * the routes remain constant while ever the server exists, and
295                  * do not need to be re-calculated.
296                  */
297
298                 Route = Above;
299                 if (Route == Utils->TreeRoot)
300                 {
301                         Route = this;
302                 }
303                 else
304                 {
305                         while (this->Route->GetParent() != Utils->TreeRoot)
306                         {
307                                 this->Route = Route->GetParent();
308                         }
309                 }
310
311                 /* Because recursive code is slow and takes a lot of resources,
312                  * we store two representations of the server tree. The first
313                  * is a recursive structure where each server references its
314                  * children and its parent, which is used for netbursts and
315                  * netsplits to dump the whole dataset to the other server,
316                  * and the second is used for very fast lookups when routing
317                  * messages and is instead a hash_map, where each item can
318                  * be referenced by its server name. The AddHashEntry()
319                  * call below automatically inserts each TreeServer class
320                  * into the hash_map as it is created. There is a similar
321                  * maintainance call in the destructor to tidy up deleted
322                  * servers.
323                  */
324
325                 this->AddHashEntry();
326         }
327
328         int QuitUsers(const std::string &reason)
329         {
330                 ServerInstance->Log(DEBUG,"Removing all users from server %s",this->ServerName.c_str());
331                 const char* reason_s = reason.c_str();
332                 std::vector<userrec*> time_to_die;
333                 for (user_hash::iterator n = ServerInstance->clientlist.begin(); n != ServerInstance->clientlist.end(); n++)
334                 {
335                         if (!strcmp(n->second->server, this->ServerName.c_str()))
336                         {
337                                 time_to_die.push_back(n->second);
338                         }
339                 }
340                 for (std::vector<userrec*>::iterator n = time_to_die.begin(); n != time_to_die.end(); n++)
341                 {
342                         userrec* a = (userrec*)*n;
343                         ServerInstance->Log(DEBUG,"Kill %s fd=%d",a->nick,a->GetFd());
344                         if (!IS_LOCAL(a))
345                                 userrec::QuitUser(ServerInstance,a,reason_s);
346                 }
347                 return time_to_die.size();
348         }
349
350         /** This method is used to add the structure to the
351          * hash_map for linear searches. It is only called
352          * by the constructors.
353          */
354         void AddHashEntry()
355         {
356                 server_hash::iterator iter = Utils->serverlist.find(this->ServerName.c_str());
357                 if (iter == Utils->serverlist.end())
358                         Utils->serverlist[this->ServerName.c_str()] = this;
359         }
360
361         /** This method removes the reference to this object
362          * from the hash_map which is used for linear searches.
363          * It is only called by the default destructor.
364          */
365         void DelHashEntry()
366         {
367                 server_hash::iterator iter = Utils->serverlist.find(this->ServerName.c_str());
368                 if (iter != Utils->serverlist.end())
369                         Utils->serverlist.erase(iter);
370         }
371
372         /** These accessors etc should be pretty self-
373          * explanitory.
374          */
375         TreeServer* GetRoute()
376         {
377                 return Route;
378         }
379
380         std::string GetName()
381         {
382                 return ServerName.c_str();
383         }
384
385         std::string GetDesc()
386         {
387                 return ServerDesc;
388         }
389
390         std::string GetVersion()
391         {
392                 return VersionString;
393         }
394
395         void SetNextPingTime(time_t t)
396         {
397                 this->NextPing = t;
398                 LastPingWasGood = false;
399         }
400
401         time_t NextPingTime()
402         {
403                 return NextPing;
404         }
405
406         bool AnsweredLastPing()
407         {
408                 return LastPingWasGood;
409         }
410
411         void SetPingFlag()
412         {
413                 LastPingWasGood = true;
414         }
415
416         int GetUserCount()
417         {
418                 return UserCount;
419         }
420
421         void AddUserCount()
422         {
423                 UserCount++;
424         }
425
426         void DelUserCount()
427         {
428                 UserCount--;
429         }
430
431         int GetOperCount()
432         {
433                 return OperCount;
434         }
435
436         TreeSocket* GetSocket()
437         {
438                 return Socket;
439         }
440
441         TreeServer* GetParent()
442         {
443                 return Parent;
444         }
445
446         void SetVersion(const std::string &Version)
447         {
448                 VersionString = Version;
449         }
450
451         unsigned int ChildCount()
452         {
453                 return Children.size();
454         }
455
456         TreeServer* GetChild(unsigned int n)
457         {
458                 if (n < Children.size())
459                 {
460                         /* Make sure they  cant request
461                          * an out-of-range object. After
462                          * all we know what these programmer
463                          * types are like *grin*.
464                          */
465                         return Children[n];
466                 }
467                 else
468                 {
469                         return NULL;
470                 }
471         }
472
473         void AddChild(TreeServer* Child)
474         {
475                 Children.push_back(Child);
476         }
477
478         bool DelChild(TreeServer* Child)
479         {
480                 for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
481                 {
482                         if (*a == Child)
483                         {
484                                 Children.erase(a);
485                                 return true;
486                         }
487                 }
488                 return false;
489         }
490
491         /** Removes child nodes of this node, and of that node, etc etc.
492          * This is used during netsplits to automatically tidy up the
493          * server tree. It is slow, we don't use it for much else.
494          */
495         bool Tidy()
496         {
497                 bool stillchildren = true;
498                 while (stillchildren)
499                 {
500                         stillchildren = false;
501                         for (std::vector<TreeServer*>::iterator a = Children.begin(); a < Children.end(); a++)
502                         {
503                                 TreeServer* s = (TreeServer*)*a;
504                                 s->Tidy();
505                                 Children.erase(a);
506                                 DELETE(s);
507                                 stillchildren = true;
508                                 break;
509                         }
510                 }
511                 return true;
512         }
513
514         ~TreeServer()
515         {
516                 /* We'd better tidy up after ourselves, eh? */
517                 this->DelHashEntry();
518         }
519 };
520
521 /** Yay for fast searches!
522  * This is hundreds of times faster than recursion
523  * or even scanning a linked list, especially when
524  * there are more than a few servers to deal with.
525  * (read as: lots).
526  */
527 TreeServer* SpanningTreeUtilities::FindServer(const std::string &ServerName)
528 {
529         server_hash::iterator iter;
530         iter = serverlist.find(ServerName.c_str());
531         if (iter != serverlist.end())
532         {
533                 return iter->second;
534         }
535         else
536         {
537                 return NULL;
538         }
539 }
540
541 /** Returns the locally connected server we must route a
542  * message through to reach server 'ServerName'. This
543  * only applies to one-to-one and not one-to-many routing.
544  * See the comments for the constructor of TreeServer
545  * for more details.
546  */
547 TreeServer* SpanningTreeUtilities::BestRouteTo(const std::string &ServerName)
548 {
549         if (ServerName.c_str() == TreeRoot->GetName())
550                 return NULL;
551         TreeServer* Found = FindServer(ServerName);
552         if (Found)
553         {
554                 return Found->GetRoute();
555         }
556         else
557         {
558                 return NULL;
559         }
560 }
561
562 /** Find the first server matching a given glob mask.
563  * Theres no find-using-glob method of hash_map [awwww :-(]
564  * so instead, we iterate over the list using an iterator
565  * and match each one until we get a hit. Yes its slow,
566  * deal with it.
567  */
568 TreeServer* SpanningTreeUtilities::FindServerMask(const std::string &ServerName)
569 {
570         for (server_hash::iterator i = serverlist.begin(); i != serverlist.end(); i++)
571         {
572                 if (match(i->first.c_str(),ServerName.c_str()))
573                         return i->second;
574         }
575         return NULL;
576 }
577
578 /* A convenient wrapper that returns true if a server exists */
579 bool SpanningTreeUtilities::IsServer(const std::string &ServerName)
580 {
581         return (FindServer(ServerName) != NULL);
582 }
583
584
585 /** Handle /RCONNECT
586  */
587 class cmd_rconnect : public command_t
588 {
589         Module* Creator;
590         SpanningTreeUtilities* Utils;
591  public:
592         cmd_rconnect (InspIRCd* Instance, Module* Callback, SpanningTreeUtilities* Util) : command_t(Instance, "RCONNECT", 'o', 2), Creator(Callback), Utils(Util)
593         {
594                 this->source = "m_spanningtree.so";
595                 syntax = "<remote-server-mask> <servermask>";
596         }
597
598         CmdResult Handle (const char** parameters, int pcnt, userrec *user)
599         {
600                 user->WriteServ("NOTICE %s :*** RCONNECT: Sending remote connect to \002%s\002 to connect server \002%s\002.",user->nick,parameters[0],parameters[1]);
601                 /* Is this aimed at our server? */
602                 if (ServerInstance->MatchText(ServerInstance->Config->ServerName,parameters[0]))
603                 {
604                         /* Yes, initiate the given connect */
605                         ServerInstance->SNO->WriteToSnoMask('l',"Remote CONNECT from %s matching \002%s\002, connecting server \002%s\002",user->nick,parameters[0],parameters[1]);
606                         const char* para[1];
607                         para[0] = parameters[1];
608                         std::string original_command = std::string("CONNECT ") + parameters[1];
609                         Creator->OnPreCommand("CONNECT", para, 1, user, true, original_command);
610
611                         return CMD_SUCCESS;
612                 }
613
614                 return CMD_FAILURE;
615         }
616 };
617  
618
619
620 /** Every SERVER connection inbound or outbound is represented by
621  * an object of type TreeSocket.
622  * TreeSockets, being inherited from InspSocket, can be tied into
623  * the core socket engine, and we cn therefore receive activity events
624  * for them, just like activex objects on speed. (yes really, that
625  * is a technical term!) Each of these which relates to a locally
626  * connected server is assocated with it, by hooking it onto a
627  * TreeSocket class using its constructor. In this way, we can
628  * maintain a list of servers, some of which are directly connected,
629  * some of which are not.
630  */
631 class TreeSocket : public InspSocket
632 {
633         SpanningTreeUtilities* Utils;
634         std::string myhost;
635         std::string in_buffer;
636         ServerState LinkState;
637         std::string InboundServerName;
638         std::string InboundDescription;
639         int num_lost_users;
640         int num_lost_servers;
641         time_t NextPing;
642         bool LastPingWasGood;
643         bool bursting;
644         AES* ctx_in;
645         AES* ctx_out;
646         unsigned int keylength;
647         std::string ModuleList;
648         std::map<std::string,std::string> CapKeys;
649
650  public:
651
652         /** Because most of the I/O gubbins are encapsulated within
653          * InspSocket, we just call the superclass constructor for
654          * most of the action, and append a few of our own values
655          * to it.
656          */
657         TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime)
658                 : InspSocket(SI, host, port, listening, maxtime), Utils(Util)
659         {
660                 myhost = host;
661                 this->LinkState = LISTENER;
662                 this->ctx_in = NULL;
663                 this->ctx_out = NULL;
664         }
665
666         TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, std::string host, int port, bool listening, unsigned long maxtime, std::string ServerName)
667                 : InspSocket(SI, host, port, listening, maxtime), Utils(Util)
668         {
669                 myhost = ServerName;
670                 this->LinkState = CONNECTING;
671                 this->ctx_in = NULL;
672                 this->ctx_out = NULL;
673         }
674
675         /** When a listening socket gives us a new file descriptor,
676          * we must associate it with a socket without creating a new
677          * connection. This constructor is used for this purpose.
678          */
679         TreeSocket(SpanningTreeUtilities* Util, InspIRCd* SI, int newfd, char* ip)
680                 : InspSocket(SI, newfd, ip), Utils(Util)
681         {
682                 this->LinkState = WAIT_AUTH_1;
683                 this->ctx_in = NULL;
684                 this->ctx_out = NULL;
685                 this->SendCapabilities();
686         }
687
688         ~TreeSocket()
689         {
690                 if (ctx_in)
691                         DELETE(ctx_in);
692                 if (ctx_out)
693                         DELETE(ctx_out);
694         }
695
696         void InitAES(std::string key,std::string SName)
697         {
698                 if (key == "")
699                         return;
700
701                 ctx_in = new AES();
702                 ctx_out = new AES();
703                 Instance->Log(DEBUG,"Initialized AES key %s",key.c_str());
704                 // key must be 16, 24, 32 etc bytes (multiple of 8)
705                 keylength = key.length();
706                 if (!(keylength == 16 || keylength == 24 || keylength == 32))
707                 {
708                         this->Instance->SNO->WriteToSnoMask('l',"\2ERROR\2: Key length for encryptionkey is not 16, 24 or 32 bytes in length!");
709                         Instance->Log(DEBUG,"Key length not 16, 24 or 32 characters!");
710                 }
711                 else
712                 {
713                         if (this->GetState() != I_ERROR)
714                         {
715                                 this->Instance->SNO->WriteToSnoMask('l',"\2AES\2: Initialized %d bit encryption to server %s",keylength*8,SName.c_str());
716                                 ctx_in->MakeKey(key.c_str(), "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\
717                                         \0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", keylength, keylength);
718                                 ctx_out->MakeKey(key.c_str(), "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\
719                                         \0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", keylength, keylength);
720                         }
721                 }
722         }
723         
724         /** When an outbound connection finishes connecting, we receive
725          * this event, and must send our SERVER string to the other
726          * side. If the other side is happy, as outlined in the server
727          * to server docs on the inspircd.org site, the other side
728          * will then send back its own server string.
729          */
730         virtual bool OnConnected()
731         {
732                 if (this->LinkState == CONNECTING)
733                 {
734                         /* we do not need to change state here. */
735                         for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
736                         {
737                                 if (x->Name == this->myhost)
738                                 {
739                                         this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] started.");
740                                         this->SendCapabilities();
741                                         if (x->EncryptionKey != "")
742                                         {
743                                                 if (!(x->EncryptionKey.length() == 16 || x->EncryptionKey.length() == 24 || x->EncryptionKey.length() == 32))
744                                                 {
745                                                         this->Instance->SNO->WriteToSnoMask('l',"\2WARNING\2: Your encryption key is NOT 16, 24 or 32 characters in length, encryption will \2NOT\2 be enabled.");
746                                                 }
747                                                 else
748                                                 {
749                                                         this->WriteLine(std::string("AES ")+this->Instance->Config->ServerName);
750                                                         this->InitAES(x->EncryptionKey,x->Name.c_str());
751                                                 }
752                                         }
753                                         /* found who we're supposed to be connecting to, send the neccessary gubbins. */
754                                         this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+x->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
755                                         return true;
756                                 }
757                         }
758                 }
759                 /* There is a (remote) chance that between the /CONNECT and the connection
760                  * being accepted, some muppet has removed the <link> block and rehashed.
761                  * If that happens the connection hangs here until it's closed. Unlikely
762                  * and rather harmless.
763                  */
764                 this->Instance->SNO->WriteToSnoMask('l',"Connection to \2"+myhost+"\2 lost link tag(!)");
765                 return true;
766         }
767         
768         virtual void OnError(InspSocketError e)
769         {
770                 /* We don't handle this method, because all our
771                  * dirty work is done in OnClose() (see below)
772                  * which is still called on error conditions too.
773                  */
774                 if (e == I_ERR_CONNECT)
775                 {
776                         this->Instance->SNO->WriteToSnoMask('l',"Connection failed: Connection to \002"+myhost+"\002 refused");
777                         Link* MyLink = Utils->FindLink(myhost);
778                         if (MyLink)
779                                 Utils->DoFailOver(MyLink);
780                 }
781         }
782
783         virtual int OnDisconnect()
784         {
785                 /* For the same reason as above, we don't
786                  * handle OnDisconnect()
787                  */
788                 return true;
789         }
790
791         /** Recursively send the server tree with distances as hops.
792          * This is used during network burst to inform the other server
793          * (and any of ITS servers too) of what servers we know about.
794          * If at any point any of these servers already exist on the other
795          * end, our connection may be terminated. The hopcounts given
796          * by this function are relative, this doesn't matter so long as
797          * they are all >1, as all the remote servers re-calculate them
798          * to be relative too, with themselves as hop 0.
799          */
800         void SendServers(TreeServer* Current, TreeServer* s, int hops)
801         {
802                 char command[1024];
803                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
804                 {
805                         TreeServer* recursive_server = Current->GetChild(q);
806                         if (recursive_server != s)
807                         {
808                                 snprintf(command,1024,":%s SERVER %s * %d :%s",Current->GetName().c_str(),recursive_server->GetName().c_str(),hops,recursive_server->GetDesc().c_str());
809                                 this->WriteLine(command);
810                                 this->WriteLine(":"+recursive_server->GetName()+" VERSION :"+recursive_server->GetVersion());
811                                 /* down to next level */
812                                 this->SendServers(recursive_server, s, hops+1);
813                         }
814                 }
815         }
816
817         std::string MyCapabilities()
818         {
819                 std::vector<std::string> modlist;
820                 std::string capabilities = "";
821
822                 for (int i = 0; i <= this->Instance->GetModuleCount(); i++)
823                 {
824                         if (this->Instance->modules[i]->GetVersion().Flags & VF_COMMON)
825                                 modlist.push_back(this->Instance->Config->module_names[i]);
826                 }
827                 sort(modlist.begin(),modlist.end());
828                 for (unsigned int i = 0; i < modlist.size(); i++)
829                 {
830                         if (i)
831                                 capabilities = capabilities + ",";
832                         capabilities = capabilities + modlist[i];
833                 }
834                 return capabilities;
835         }
836         
837         void SendCapabilities()
838         {
839                 irc::commasepstream modulelist(MyCapabilities());
840
841                 this->WriteLine("CAPAB START");
842
843                 /* Send module names, split at 509 length */
844                 std::string item = "*";
845                 std::string line = "CAPAB MODULES ";
846                 while ((item = modulelist.GetToken()) != "")
847                 {
848                         if (line.length() + item.length() + 1 > 509)
849                         {
850                                 this->WriteLine(line);
851                                 line = "CAPAB MODULES ";
852                         }
853
854                         if (line != "CAPAB MODULES ")
855                                 line.append(",");
856
857                         line.append(item);
858                 }
859                 if (line != "CAPAB MODULES ")
860                         this->WriteLine(line);
861
862                 int ip6 = 0;
863                 int ip6support = 0;
864 #ifdef IPV6
865                 ip6 = 1;
866 #endif
867 #ifdef SUPPORT_IP6LINKS
868                 ip6support = 1;
869 #endif
870                 this->WriteLine("CAPAB CAPABILITIES :NICKMAX="+ConvToStr(NICKMAX)+" HALFOP="+ConvToStr(this->Instance->Config->AllowHalfop)+" CHANMAX="+ConvToStr(CHANMAX)+" MAXMODES="+ConvToStr(MAXMODES)+" IDENTMAX="+ConvToStr(IDENTMAX)+" MAXQUIT="+ConvToStr(MAXQUIT)+" MAXTOPIC="+ConvToStr(MAXTOPIC)+" MAXKICK="+ConvToStr(MAXKICK)+" MAXGECOS="+ConvToStr(MAXGECOS)+" MAXAWAY="+ConvToStr(MAXAWAY)+" IP6NATIVE="+ConvToStr(ip6)+" IP6SUPPORT="+ConvToStr(ip6support)+" PROTOCOL="+ConvToStr(ProtocolVersion));
871
872                 this->WriteLine("CAPAB END");
873         }
874
875         /* Check a comma seperated list for an item */
876         bool HasItem(const std::string &list, const std::string &item)
877         {
878                 irc::commasepstream seplist(list);
879
880                 std::string item2 = "*";
881                 while ((item2 = seplist.GetToken()) != "")
882                 {
883                         if (item2 == item)
884                                 return true;
885                 }
886
887                 return false;
888         }
889
890         /* Isolate and return the elements that are different between two comma seperated lists */
891         std::string ListDifference(const std::string &one, const std::string &two)
892         {
893                 irc::commasepstream list_one(one);
894                 std::string item = "*";
895                 std::string result = "";
896                 while ((item = list_one.GetToken()) != "")
897                 {
898                         if (!HasItem(two, item))
899                         {
900                                 result.append(" ");
901                                 result.append(item);
902                         }
903                 }
904                 return result;
905         }
906
907         bool Capab(const std::deque<std::string> &params)
908         {
909                 if (params.size() < 1)
910                 {
911                         this->WriteLine("ERROR :Invalid number of parameters for CAPAB - Mismatched version");
912                         return false;
913                 }
914
915                 if (params[0] == "START")
916                 {
917                         this->ModuleList = "";
918                         this->CapKeys.clear();
919                 }
920                 else if (params[0] == "END")
921                 {
922                         std::string reason = "";
923                         int ip6support = 0;
924 #ifdef SUPPORT_IP6LINKS
925                         ip6support = 1;
926 #endif
927                         /* Compare ModuleList and check CapKeys...
928                          * Maybe this could be tidier? -- Brain
929                          */
930                         if ((this->ModuleList != this->MyCapabilities()) && (this->ModuleList.length()))
931                         {
932                                 std::string diff = ListDifference(this->ModuleList, this->MyCapabilities());
933                                 if (!diff.length())
934                                 {
935                                         diff = "your server:" + ListDifference(this->MyCapabilities(), this->ModuleList);
936                                 }
937                                 else
938                                 {
939                                         diff = "this server:" + diff;
940                                 }
941                                 if (diff.length() == 12)
942                                         reason = "Module list in CAPAB is not alphabetically ordered, cannot compare lists.";
943                                 else
944                                         reason = "Modules loaded on these servers are not correctly matched, these modules are not loaded on " + diff;
945                         }
946
947                         if (((this->CapKeys.find("IP6SUPPORT") == this->CapKeys.end()) && (ip6support)) || ((this->CapKeys.find("IP6SUPPORT") != this->CapKeys.end()) && (this->CapKeys.find("IP6SUPPORT")->second != ConvToStr(ip6support))))
948                                 reason = "We don't both support linking to IPV6 servers";
949
950                         if (((this->CapKeys.find("IP6NATIVE") != this->CapKeys.end()) && (this->CapKeys.find("IP6NATIVE")->second == "1")) && (!ip6support))
951                                 reason = "The remote server is IPV6 native, and we don't support linking to IPV6 servers";
952
953                         if (((this->CapKeys.find("NICKMAX") == this->CapKeys.end()) || ((this->CapKeys.find("NICKMAX") != this->CapKeys.end()) && (this->CapKeys.find("NICKMAX")->second != ConvToStr(NICKMAX)))))
954                                 reason = "Maximum nickname lengths differ or remote nickname length not specified";
955
956                         if (((this->CapKeys.find("PROTOCOL") == this->CapKeys.end()) || ((this->CapKeys.find("PROTOCOL") != this->CapKeys.end()) && (this->CapKeys.find("PROTOCOL")->second != ConvToStr(ProtocolVersion)))))
957                         {
958                                 if (this->CapKeys.find("PROTOCOL") != this->CapKeys.end())
959                                 {
960                                         reason = "Mismatched protocol versions "+this->CapKeys.find("PROTOCOL")->second+" and "+ConvToStr(ProtocolVersion);
961                                 }
962                                 else
963                                 {
964                                         reason = "Protocol version not specified";
965                                 }
966                         }
967
968                         if (((this->CapKeys.find("HALFOP") == this->CapKeys.end()) && (Instance->Config->AllowHalfop)) || ((this->CapKeys.find("HALFOP") != this->CapKeys.end()) && (this->CapKeys.find("HALFOP")->second != ConvToStr(Instance->Config->AllowHalfop))))
969                                 reason = "We don't both have halfop support enabled/disabled identically";
970
971                         if (((this->CapKeys.find("IDENTMAX") == this->CapKeys.end()) || ((this->CapKeys.find("IDENTMAX") != this->CapKeys.end()) && (this->CapKeys.find("IDENTMAX")->second != ConvToStr(IDENTMAX)))))
972                                 reason = "Maximum ident lengths differ or remote ident length not specified";
973
974                         if (((this->CapKeys.find("CHANMAX") == this->CapKeys.end()) || ((this->CapKeys.find("CHANMAX") != this->CapKeys.end()) && (this->CapKeys.find("CHANMAX")->second != ConvToStr(CHANMAX)))))
975                                 reason = "Maximum channel lengths differ or remote channel length not specified";
976
977                         if (((this->CapKeys.find("MAXMODES") == this->CapKeys.end()) || ((this->CapKeys.find("MAXMODES") != this->CapKeys.end()) && (this->CapKeys.find("MAXMODES")->second != ConvToStr(MAXMODES)))))
978                                 reason = "Maximum modes per line differ or remote modes per line not specified";
979
980                         if (((this->CapKeys.find("MAXQUIT") == this->CapKeys.end()) || ((this->CapKeys.find("MAXQUIT") != this->CapKeys.end()) && (this->CapKeys.find("MAXQUIT")->second != ConvToStr(MAXQUIT)))))
981                                 reason = "Maximum quit lengths differ or remote quit length not specified";
982
983                         if (((this->CapKeys.find("MAXTOPIC") == this->CapKeys.end()) || ((this->CapKeys.find("MAXTOPIC") != this->CapKeys.end()) && (this->CapKeys.find("MAXTOPIC")->second != ConvToStr(MAXTOPIC)))))
984                                 reason = "Maximum topic lengths differ or remote topic length not specified";
985
986                         if (((this->CapKeys.find("MAXKICK") == this->CapKeys.end()) || ((this->CapKeys.find("MAXKICK") != this->CapKeys.end()) && (this->CapKeys.find("MAXKICK")->second != ConvToStr(MAXKICK)))))
987                                 reason = "Maximum kick lengths differ or remote kick length not specified";
988
989                         if (((this->CapKeys.find("MAXGECOS") == this->CapKeys.end()) || ((this->CapKeys.find("MAXGECOS") != this->CapKeys.end()) && (this->CapKeys.find("MAXGECOS")->second != ConvToStr(MAXGECOS)))))
990                                 reason = "Maximum GECOS (fullname) lengths differ or remote GECOS length not specified";
991
992                         if (((this->CapKeys.find("MAXAWAY") == this->CapKeys.end()) || ((this->CapKeys.find("MAXAWAY") != this->CapKeys.end()) && (this->CapKeys.find("MAXAWAY")->second != ConvToStr(MAXAWAY)))))
993                                 reason = "Maximum awaymessage lengths differ or remote awaymessage length not specified";
994
995                         if (reason.length())
996                         {
997                                 this->WriteLine("ERROR :CAPAB negotiation failed: "+reason);
998                                 return false;
999                         }
1000                 }
1001                 else if ((params[0] == "MODULES") && (params.size() == 2))
1002                 {
1003                         if (!this->ModuleList.length())
1004                         {
1005                                 this->ModuleList.append(params[1]);
1006                         }
1007                         else
1008                         {
1009                                 this->ModuleList.append(",");
1010                                 this->ModuleList.append(params[1]);
1011                         }
1012                 }
1013                 else if ((params[0] == "CAPABILITIES") && (params.size() == 2))
1014                 {
1015                         irc::tokenstream capabs(params[1]);
1016                         std::string item = "*";
1017                         while ((item = capabs.GetToken()) != "")
1018                         {
1019                                 /* Process each key/value pair */
1020                                 std::string::size_type equals = item.rfind('=');
1021                                 if (equals != std::string::npos)
1022                                 {
1023                                         std::string var = item.substr(0, equals);
1024                                         std::string value = item.substr(equals+1, item.length());
1025                                         this->Instance->Log(DEBUG,"Key='%s' Value='%s'",var.c_str(),value.c_str());
1026                                         CapKeys[var] = value;
1027                                 }
1028                         }
1029                 }
1030
1031                 return true;
1032         }
1033
1034         /** This function forces this server to quit, removing this server
1035          * and any users on it (and servers and users below that, etc etc).
1036          * It's very slow and pretty clunky, but luckily unless your network
1037          * is having a REAL bad hair day, this function shouldnt be called
1038          * too many times a month ;-)
1039          */
1040         void SquitServer(std::string &from, TreeServer* Current)
1041         {
1042                 /* recursively squit the servers attached to 'Current'.
1043                  * We're going backwards so we don't remove users
1044                  * while we still need them ;)
1045                  */
1046                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
1047                 {
1048                         TreeServer* recursive_server = Current->GetChild(q);
1049                         this->SquitServer(from,recursive_server);
1050                 }
1051                 /* Now we've whacked the kids, whack self */
1052                 num_lost_servers++;
1053                 num_lost_users += Current->QuitUsers(from);
1054         }
1055
1056         /** This is a wrapper function for SquitServer above, which
1057          * does some validation first and passes on the SQUIT to all
1058          * other remaining servers.
1059          */
1060         void Squit(TreeServer* Current, const std::string &reason)
1061         {
1062                 if ((Current) && (Current != Utils->TreeRoot))
1063                 {
1064                         Event rmode((char*)Current->GetName().c_str(), (Module*)Utils->Creator, "lost_server");
1065                         rmode.Send(Instance);
1066
1067                         std::deque<std::string> params;
1068                         params.push_back(Current->GetName());
1069                         params.push_back(":"+reason);
1070                         Utils->DoOneToAllButSender(Current->GetParent()->GetName(),"SQUIT",params,Current->GetName());
1071                         if (Current->GetParent() == Utils->TreeRoot)
1072                         {
1073                                 this->Instance->WriteOpers("Server \002"+Current->GetName()+"\002 split: "+reason);
1074                         }
1075                         else
1076                         {
1077                                 this->Instance->WriteOpers("Server \002"+Current->GetName()+"\002 split from server \002"+Current->GetParent()->GetName()+"\002 with reason: "+reason);
1078                         }
1079                         num_lost_servers = 0;
1080                         num_lost_users = 0;
1081                         std::string from = Current->GetParent()->GetName()+" "+Current->GetName();
1082                         SquitServer(from, Current);
1083                         Current->Tidy();
1084                         Current->GetParent()->DelChild(Current);
1085                         DELETE(Current);
1086                         this->Instance->WriteOpers("Netsplit complete, lost \002%d\002 users on \002%d\002 servers.", num_lost_users, num_lost_servers);
1087                 }
1088                 else
1089                 {
1090                         Instance->Log(DEFAULT,"Squit from unknown server");
1091                 }
1092         }
1093
1094         /** FMODE command - server mode with timestamp checks */
1095         bool ForceMode(const std::string &source, std::deque<std::string> &params)
1096         {
1097                 /* Chances are this is a 1.0 FMODE without TS */
1098                 if (params.size() < 3)
1099                 {
1100                         this->WriteLine("ERROR :Version 1.0 FMODE sent to version 1.1 server");
1101                         return false;
1102                 }
1103                 
1104                 bool smode = false;
1105                 std::string sourceserv;
1106
1107                 /* Are we dealing with an FMODE from a user, or from a server? */
1108                 userrec* who = this->Instance->FindNick(source);
1109                 if (who)
1110                 {
1111                         /* FMODE from a user, set sourceserv to the users server name */
1112                         sourceserv = who->server;
1113                 }
1114                 else
1115                 {
1116                         /* FMODE from a server, create a fake user to receive mode feedback */
1117                         who = new userrec(this->Instance);
1118                         who->SetFd(FD_MAGIC_NUMBER);
1119                         smode = true;           /* Setting this flag tells us we should free the userrec later */
1120                         sourceserv = source;    /* Set sourceserv to the actual source string */
1121                 }
1122                 const char* modelist[64];
1123                 time_t TS = 0;
1124                 int n = 0;
1125                 memset(&modelist,0,sizeof(modelist));
1126                 for (unsigned int q = 0; (q < params.size()) && (q < 64); q++)
1127                 {
1128                         if (q == 1)
1129                         {
1130                                 /* The timestamp is in this position.
1131                                  * We don't want to pass that up to the
1132                                  * server->client protocol!
1133                                  */
1134                                 TS = atoi(params[q].c_str());
1135                         }
1136                         else
1137                         {
1138                                 /* Everything else is fine to append to the modelist */
1139                                 modelist[n++] = params[q].c_str();
1140                         }
1141                                 
1142                 }
1143                 /* Extract the TS value of the object, either userrec or chanrec */
1144                 userrec* dst = this->Instance->FindNick(params[0]);
1145                 chanrec* chan = NULL;
1146                 time_t ourTS = 0;
1147                 if (dst)
1148                 {
1149                         ourTS = dst->age;
1150                 }
1151                 else
1152                 {
1153                         chan = this->Instance->FindChan(params[0]);
1154                         if (chan)
1155                         {
1156                                 ourTS = chan->age;
1157                         }
1158                         else
1159                                 /* Oops, channel doesnt exist! */
1160                                 return true;
1161                 }
1162
1163                 /* TS is equal: Merge the mode changes, use voooodoooooo on modes
1164                  * with parameters.
1165                  */
1166                 if (TS == ourTS)
1167                 {
1168                         Instance->Log(DEBUG,"Entering TS equality check");
1169                         ModeHandler* mh = NULL;
1170                         unsigned long paramptr = 3;
1171                         std::string to_bounce = "";
1172                         std::string to_keep = "";
1173                         std::vector<std::string> params_to_keep;
1174                         std::string params_to_bounce = "";
1175                         bool adding = true;
1176                         char cur_change = 1;
1177                         char old_change = 0;
1178                         char old_bounce_change = 0;
1179                         /* Merge modes, basically do special stuff to mode with params */
1180                         for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
1181                         {
1182                                 switch (*x)
1183                                 {
1184                                         case '-':
1185                                                 adding = false;
1186                                         break;
1187                                         case '+':
1188                                                 adding = true;
1189                                         break;
1190                                         default:
1191                                                 if (adding)
1192                                                 {
1193                                                         /* We only care about whats being set,
1194                                                          * not whats being unset
1195                                                          */
1196                                                         mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1197
1198                                                         if ((mh) && (mh->GetNumParams(adding) > 0) && (!mh->IsListMode()))
1199                                                         {
1200                                                                 /* We only want to do special things to
1201                                                                  * modes with parameters, we are going to rewrite
1202                                                                  * those parameters
1203                                                                  */
1204                                                                 ModePair ret;
1205                                                                 adding ? cur_change = '+' : cur_change = '-';
1206
1207                                                                 ret = mh->ModeSet(smode ? NULL : who, dst, chan, params[paramptr]);
1208
1209                                                                 /* The mode is set here, check which we should keep */
1210                                                                 if (ret.first)
1211                                                                 {
1212                                                                         bool which_to_keep = mh->CheckTimeStamp(TS, ourTS, params[paramptr], ret.second, chan);
1213
1214                                                                         if (which_to_keep == true)
1215                                                                         {
1216                                                                                 /* Keep ours, bounce theirs:
1217                                                                                  * Send back ours to them and
1218                                                                                  * drop their mode changs
1219                                                                                  */
1220                                                                                 adding ? cur_change = '+' : cur_change = '-';
1221                                                                                 if (cur_change != old_bounce_change)
1222                                                                                         to_bounce += cur_change;
1223                                                                                 to_bounce += *x;
1224                                                                                 old_bounce_change = cur_change;
1225
1226                                                                                 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1227                                                                                         params_to_bounce.append(" ").append(ret.second);
1228                                                                         }
1229                                                                         else
1230                                                                         {
1231                                                                                 /* Keep theirs: Accept their mode change,
1232                                                                                  * do nothing else
1233                                                                                  */
1234                                                                                 adding ? cur_change = '+' : cur_change = '-';
1235                                                                                 if (cur_change != old_change)
1236                                                                                         to_keep += cur_change;
1237                                                                                 to_keep += *x;
1238                                                                                 old_change = cur_change;
1239
1240                                                                                 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1241                                                                                         params_to_keep.push_back(params[paramptr]);
1242                                                                         }
1243                                                                 }
1244                                                                 else
1245                                                                 {
1246                                                                         /* Mode isnt set here, we want it */
1247                                                                         adding ? cur_change = '+' : cur_change = '-';
1248                                                                         if (cur_change != old_change)
1249                                                                                 to_keep += cur_change;
1250                                                                         to_keep += *x;
1251                                                                         old_change = cur_change;
1252
1253                                                                         if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1254                                                                                 params_to_keep.push_back(params[paramptr]);
1255                                                                 }
1256
1257                                                                 paramptr++;
1258                                                         }
1259                                                         else
1260                                                         {
1261                                                                 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1262
1263                                                                 if (mh)
1264                                                                 {
1265                                                                         adding ? cur_change = '+' : cur_change = '-';
1266         
1267                                                                         /* Just keep this, safe to merge with no checks
1268                                                                          * it has no parameters
1269                                                                          */
1270         
1271                                                                         if (cur_change != old_change)
1272                                                                                 to_keep += cur_change;
1273                                                                         to_keep += *x;
1274                                                                         old_change = cur_change;
1275         
1276                                                                         if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1277                                                                         {
1278                                                                                 Instance->Log(DEBUG,"Mode removal %d %d",adding, mh->GetNumParams(adding));
1279                                                                                 params_to_keep.push_back(params[paramptr++]);
1280                                                                         }
1281                                                                 }
1282                                                         }
1283                                                 }
1284                                                 else
1285                                                 {
1286                                                         mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1287
1288                                                         if (mh)
1289                                                         {
1290                                                                 /* Taking a mode away */
1291                                                                 adding ? cur_change = '+' : cur_change = '-';
1292
1293                                                                 if (cur_change != old_change)
1294                                                                         to_keep += cur_change;
1295                                                                 to_keep += *x;
1296                                                                 old_change = cur_change;
1297
1298                                                                 if ((mh->GetNumParams(adding) > 0) && (paramptr < params.size()))
1299                                                                         params_to_keep.push_back(params[paramptr++]);
1300                                                         }
1301                                                 }
1302                                         break;
1303                                 }
1304                         }
1305
1306                         if (to_bounce.length())
1307                         {
1308                                 std::deque<std::string> newparams;
1309                                 newparams.push_back(params[0]);
1310                                 newparams.push_back(ConvToStr(ourTS));
1311                                 newparams.push_back(to_bounce+params_to_bounce);
1312                                 Instance->Log(DEBUG,"BOUNCE BACK: %s",(to_bounce+params_to_bounce).c_str());
1313                                 Utils->DoOneToOne(this->Instance->Config->ServerName,"FMODE",newparams,sourceserv);
1314                         }
1315
1316                         if (to_keep.length())
1317                         {
1318                                 unsigned int n = 2;
1319                                 unsigned int q = 0;
1320                                 modelist[0] = params[0].c_str();
1321                                 modelist[1] = to_keep.c_str();
1322
1323                                 if (params_to_keep.size() > 0)
1324                                 {
1325                                         for (q = 0; (q < params_to_keep.size()) && (q < 64); q++)
1326                                         {
1327                                                 Instance->Log(DEBUG,"KEEP Item %d of %d: %s", q, params_to_keep.size(), params_to_keep[q].c_str());
1328                                                 modelist[n++] = params_to_keep[q].c_str();
1329                                         }
1330                                 }
1331
1332                                 if (smode)
1333                                 {
1334                                         Instance->Log(DEBUG,"Send mode");
1335                                         this->Instance->SendMode(modelist, n, who);
1336                                 }
1337                                 else
1338                                 {
1339                                         Instance->Log(DEBUG,"Send mode client");
1340                                         this->Instance->CallCommandHandler("MODE", modelist, n, who);
1341                                 }
1342
1343                                 /* HOT POTATO! PASS IT ON! */
1344                                 Utils->DoOneToAllButSender(source,"FMODE",params,sourceserv);
1345                         }
1346                 }
1347                 else
1348                 /* U-lined servers always win regardless of their TS */
1349                 if ((TS > ourTS) && (!this->Instance->ULine(source.c_str())))
1350                 {
1351                         /* Bounce the mode back to its sender.* We use our lower TS, so the other end
1352                          * SHOULD accept it, if its clock is right.
1353                          *
1354                          * NOTE: We should check that we arent bouncing anything thats already set at this end.
1355                          * If we are, bounce +ourmode to 'reinforce' it. This prevents desyncs.
1356                          * e.g. They send +l 50, we have +l 10 set. rather than bounce -l 50, we bounce +l 10.
1357                          *
1358                          * Thanks to jilles for pointing out this one-hell-of-an-issue before i even finished
1359                          * writing the code. It took me a while to come up with this solution.
1360                          *
1361                          * XXX: BE SURE YOU UNDERSTAND THIS CODE FULLY BEFORE YOU MESS WITH IT.
1362                          */
1363
1364                         std::deque<std::string> newparams;      /* New parameter list we send back */
1365                         newparams.push_back(params[0]);         /* Target, user or channel */
1366                         newparams.push_back(ConvToStr(ourTS));  /* Timestamp value of the target */
1367                         newparams.push_back("");                /* This contains the mode string. For now
1368                                                                  * it's empty, we fill it below.
1369                                                                  */
1370
1371                         /* Intelligent mode bouncing. Don't just invert, reinforce any modes which are already
1372                          * set to avoid a desync here.
1373                          */
1374                         std::string modebounce = "";
1375                         bool adding = true;
1376                         unsigned int t = 3;
1377                         ModeHandler* mh = NULL;
1378                         char cur_change = 1;
1379                         char old_change = 0;
1380                         for (std::string::iterator x = params[2].begin(); x != params[2].end(); x++)
1381                         {
1382                                 /* Iterate over all mode chars in the sent set */
1383                                 switch (*x)
1384                                 {
1385                                         /* Adding or subtracting modes? */
1386                                         case '-':
1387                                                 adding = false;
1388                                         break;
1389                                         case '+':
1390                                                 adding = true;
1391                                         break;
1392                                         default:
1393                                                 /* Find the mode handler for this mode */
1394                                                 mh = this->Instance->Modes->FindMode(*x, chan ? MODETYPE_CHANNEL : MODETYPE_USER);
1395
1396                                                 /* Got a mode handler?
1397                                                  * This also prevents us bouncing modes we have no handler for.
1398                                                  */
1399                                                 if (mh)
1400                                                 {
1401                                                         ModePair ret;
1402                                                         std::string p = "";
1403
1404                                                         /* Does the mode require a parameter right now?
1405                                                          * If it does, fetch it if we can
1406                                                          */
1407                                                         if ((mh->GetNumParams(adding) > 0) && (t < params.size()))
1408                                                                 p = params[t++];
1409
1410                                                         /* Call the ModeSet method to determine if its set with the
1411                                                          * given parameter here or not.
1412                                                          */
1413                                                         ret = mh->ModeSet(smode ? NULL : who, dst, chan, p);
1414
1415                                                         /* XXX: Really. Dont ask.
1416                                                          * Determine from if its set combined with what the current
1417                                                          * 'state' is (adding or not) as to wether we should 'invert'
1418                                                          * or 'reinforce' the mode change
1419                                                          */
1420                                                         (!ret.first ? (adding ? cur_change = '-' : cur_change = '+') : (!adding ? cur_change = '-' : cur_change = '+'));
1421
1422                                                         /* Quickly determine if we have 'flipped' from + to -,
1423                                                          * or - to +, to prevent unneccessary +/- chars in the
1424                                                          * output string that waste bandwidth
1425                                                          */
1426                                                         if (cur_change != old_change)
1427                                                                 modebounce += cur_change;
1428                                                         old_change = cur_change;
1429
1430                                                         /* Add the mode character to the output string */
1431                                                         modebounce += mh->GetModeChar();
1432
1433                                                         /* We got a parameter back from ModeHandler::ModeSet,
1434                                                          * are we supposed to be sending one out right now?
1435                                                          */
1436                                                         if (ret.second.length())
1437                                                         {
1438                                                                 if (mh->GetNumParams(cur_change == '+') > 0)
1439                                                                         /* Yes we're supposed to be sending out
1440                                                                          * the parameter. Make sure it goes
1441                                                                          */
1442                                                                         newparams.push_back(ret.second);
1443                                                         }
1444
1445                                                 }
1446                                         break;
1447                                 }
1448                         }
1449                         
1450                         /* Update the parameters for FMODE with the new 'bounced' string */
1451                         newparams[2] = modebounce;
1452                         /* Only send it back the way it came, no need to send it anywhere else */
1453                         Utils->DoOneToOne(this->Instance->Config->ServerName,"FMODE",newparams,sourceserv);
1454                         Instance->Log(DEBUG,"FMODE bounced intelligently, our TS less than theirs and the other server is NOT a uline.");
1455                 }
1456                 else
1457                 {
1458                         Instance->Log(DEBUG,"Allow modes, TS lower for sender");
1459                         /* The server was ulined, but something iffy is up with the TS.
1460                          * Sound the alarm bells!
1461                          */
1462                         if ((this->Instance->ULine(sourceserv.c_str())) && (TS > ourTS))
1463                         {
1464                                 this->Instance->WriteOpers("\2WARNING!\2 U-Lined server '%s' has bad TS for '%s' (accepted change): \2SYNC YOUR CLOCKS\2 to avoid this notice",sourceserv.c_str(),params[0].c_str());
1465                         }
1466                         /* Allow the mode, route it to either server or user command handling */
1467                         if (smode)
1468                                 this->Instance->SendMode(modelist,n,who);
1469                         else
1470                                 this->Instance->CallCommandHandler("MODE", modelist, n, who);
1471
1472                         /* HOT POTATO! PASS IT ON! */
1473                         Utils->DoOneToAllButSender(source,"FMODE",params,sourceserv);
1474                 }
1475                 /* Are we supposed to free the userrec? */
1476                 if (smode)
1477                         DELETE(who);
1478
1479                 return true;
1480         }
1481
1482         /** FTOPIC command */
1483         bool ForceTopic(const std::string &source, std::deque<std::string> &params)
1484         {
1485                 if (params.size() != 4)
1486                         return true;
1487                 time_t ts = atoi(params[1].c_str());
1488                 std::string nsource = source;
1489
1490                 chanrec* c = this->Instance->FindChan(params[0]);
1491                 if (c)
1492                 {
1493                         if ((ts >= c->topicset) || (!*c->topic))
1494                         {
1495                                 std::string oldtopic = c->topic;
1496                                 strlcpy(c->topic,params[3].c_str(),MAXTOPIC);
1497                                 strlcpy(c->setby,params[2].c_str(),NICKMAX-1);
1498                                 c->topicset = ts;
1499                                 /* if the topic text is the same as the current topic,
1500                                  * dont bother to send the TOPIC command out, just silently
1501                                  * update the set time and set nick.
1502                                  */
1503                                 if (oldtopic != params[3])
1504                                 {
1505                                         userrec* user = this->Instance->FindNick(source);
1506                                         if (!user)
1507                                         {
1508                                                 c->WriteChannelWithServ(source.c_str(), "TOPIC %s :%s", c->name, c->topic);
1509                                         }
1510                                         else
1511                                         {
1512                                                 c->WriteChannel(user, "TOPIC %s :%s", c->name, c->topic);
1513                                                 nsource = user->server;
1514                                         }
1515                                         /* all done, send it on its way */
1516                                         params[3] = ":" + params[3];
1517                                         Utils->DoOneToAllButSender(source,"FTOPIC",params,nsource);
1518                                 }
1519                         }
1520                         
1521                 }
1522
1523                 return true;
1524         }
1525
1526         /** FJOIN, similar to TS6 SJOIN, but not quite. */
1527         bool ForceJoin(const std::string &source, std::deque<std::string> &params)
1528         {
1529                 /* 1.1 FJOIN works as follows:
1530                  *
1531                  * Each FJOIN is sent along with a timestamp, and the side with the lowest
1532                  * timestamp 'wins'. From this point on we will refer to this side as the
1533                  * winner. The side with the higher timestamp loses, from this point on we
1534                  * will call this side the loser or losing side. This should be familiar to
1535                  * anyone who's dealt with dreamforge or TS6 before.
1536                  *
1537                  * When two sides of a split heal and this occurs, the following things
1538                  * will happen:
1539                  *
1540                  * If the timestamps are exactly equal, both sides merge their privilages
1541                  * and users, as in InspIRCd 1.0 and ircd2.8. The channels have not been
1542                  * re-created during a split, this is safe to do.
1543                  *
1544                  *
1545                  * If the timestamps are NOT equal, the losing side removes all privilage
1546                  * modes from all of its users that currently exist in the channel, before
1547                  * introducing new users into the channel which are listed in the FJOIN
1548                  * command's parameters. This means, all modes +ohv, and privilages added
1549                  * by modules, such as +qa. The losing side then LOWERS its timestamp value
1550                  * of the channel to match that of the winning side, and the modes of the
1551                  * users of the winning side are merged in with the losing side. The loser
1552                  * then sends out a set of FMODE commands which 'confirm' that it just
1553                  * removed all privilage modes from its existing users, which allows for
1554                  * services packages to still work correctly without needing to know the
1555                  * timestamping rules which InspIRCd follows. In TS6 servers this is always
1556                  * a problem, and services packages must contain code which explicitly
1557                  * behaves as TS6 does, removing ops from the losing side of a split where
1558                  * neccessary within its internal records, as this state information is
1559                  * not explicitly echoed out in that protocol.
1560                  *
1561                  * The winning side on the other hand will ignore all user modes from the
1562                  * losing side, so only its own modes get applied. Life is simple for those
1563                  * who succeed at internets. :-)
1564                  *
1565                  * NOTE: Unlike TS6 and dreamforge and other protocols which have SJOIN,
1566                  * FJOIN does not contain the simple-modes such as +iklmnsp. Why not,
1567                  * you ask? Well, quite simply because we don't need to. They'll be sent
1568                  * after the FJOIN by FMODE, and FMODE is timestamped, so in the event
1569                  * the losing side sends any modes for the channel which shouldnt win,
1570                  * they wont as their timestamp will be too high :-)
1571                  */
1572
1573                 if (params.size() < 3)
1574                         return true;
1575
1576                 char first[MAXBUF];             /* The first parameter of the mode command */
1577                 char modestring[MAXBUF];        /* The mode sequence (2nd parameter) of the mode command */
1578                 char* mode_users[127];          /* The values used by the mode command */
1579                 memset(&mode_users,0,sizeof(mode_users));       /* Initialize mode parameters */
1580                 mode_users[0] = first;          /* Set this up to be our on-stack value */
1581                 mode_users[1] = modestring;     /* Same here as above */
1582                 strcpy(modestring,"+");         /* Initialize the mode sequence to just '+' */
1583                 unsigned int modectr = 2;       /* Pointer to the third mode parameter (e.g. the one after the +-sequence) */
1584                 
1585                 userrec* who = NULL;                    /* User we are currently checking */
1586                 std::string channel = params[0];        /* Channel name, as a string */
1587                 time_t TS = atoi(params[1].c_str());    /* Timestamp given to us for remote side */
1588                 
1589                 /* Try and find the channel */
1590                 chanrec* chan = this->Instance->FindChan(channel);
1591
1592                 /* Initialize channel name in the mode parameters */
1593                 strlcpy(mode_users[0],channel.c_str(),MAXBUF);
1594
1595                 /* default TS is a high value, which if we dont have this
1596                  * channel will let the other side apply their modes.
1597                  */
1598                 time_t ourTS = Instance->Time(true)+600;
1599
1600                 /* Does this channel exist? if it does, get its REAL timestamp */
1601                 if (chan)
1602                         ourTS = chan->age;
1603
1604                 /* In 1.1, if they have the newer channel, we immediately clear
1605                  * all status modes from our users. We then accept their modes.
1606                  * If WE have the newer channel its the other side's job to do this.
1607                  * Note that this causes the losing server to send out confirming
1608                  * FMODE lines.
1609                  */
1610                 if (ourTS > TS)
1611                 {
1612                         std::deque<std::string> param_list;
1613
1614                         if (chan)
1615                                 chan->age = TS;
1616
1617                         /* Lower the TS here */
1618                         if (Utils->AnnounceTSChange && chan)
1619                                 chan->WriteChannelWithServ(Instance->Config->ServerName,
1620                                 "NOTICE %s :TS for %s changed from %lu to %lu", chan->name, chan->name, ourTS, TS);
1621                         ourTS = TS;
1622
1623                         param_list.push_back(channel);
1624                         /* Zap all the privilage modes on our side */
1625                         this->RemoveStatus(Instance->Config->ServerName, param_list);
1626                 }
1627
1628                 /* Put the final parameter of the FJOIN into a tokenstream ready to split it */
1629                 irc::tokenstream users(params[2]);
1630                 std::string item = "*";
1631
1632                 /* do this first, so our mode reversals are correctly received by other servers
1633                  * if there is a TS collision.
1634                  */
1635                 params[2] = ":" + params[2];
1636                 Utils->DoOneToAllButSender(source,"FJOIN",params,source);
1637
1638                 /* Now, process every 'prefixes,nick' pair */
1639                 while (item != "")
1640                 {
1641                         /* Find next user */
1642                         item = users.GetToken();
1643
1644                         const char* usr = item.c_str();
1645
1646                         /* Safety check just to make sure someones not sent us an FJOIN full of spaces
1647                          * (is this even possible?) */
1648                         if (usr && *usr)
1649                         {
1650                                 const char* permissions = usr;
1651                                 int ntimes = 0;
1652                                 char* nm = new char[MAXBUF];
1653                                 char* tnm = nm;
1654
1655                                 /* Iterate through all the prefix values, convert them from prefixes
1656                                  * to mode letters, and append them to the mode sequence
1657                                  */
1658                                 while ((*permissions) && (*permissions != ',') && (ntimes < MAXBUF))
1659                                 {
1660                                         ModeHandler* mh = Instance->Modes->FindPrefix(*permissions);
1661                                         if (mh)
1662                                         {
1663                                                 /* This is a valid prefix */
1664                                                 ntimes++;
1665                                                 *tnm++ = mh->GetModeChar();
1666                                         }
1667                                         else
1668                                         {
1669                                                 /* Not a valid prefix...
1670                                                  * danger bill bobbertson! (that's will robinsons older brother ;-) ...)
1671                                                  */
1672                                                 this->Instance->WriteOpers("ERROR: We received a user with an unknown prefix '%c'. Closed connection to avoid a desync.",*permissions);
1673                                                 this->WriteLine(std::string("ERROR :Invalid prefix '")+(*permissions)+"' in FJOIN");
1674                                                 return false;
1675                                         }
1676                                         usr++;
1677                                         permissions++;
1678                                 }
1679
1680                                 /* Null terminate modes */
1681                                 *tnm = 0;
1682                                 /* Advance past the comma, to the nick */
1683                                 usr++;
1684
1685                                 /* Check the user actually exists */
1686                                 who = this->Instance->FindNick(usr);
1687                                 if (who)
1688                                 {
1689                                         /* Did they get any modes? How many times? */
1690                                         strlcat(modestring, nm, MAXBUF);
1691                                         for (int k = 0; k < ntimes; k++)
1692                                                 mode_users[modectr++] = strdup(usr);
1693
1694                                         /* Free temporary buffer used for mode sequence */
1695                                         delete[] nm;
1696
1697                                         /* Check that the user's 'direction' is correct
1698                                          * based on the server sending the FJOIN. We must
1699                                          * check each nickname in turn, because the origin of
1700                                          * the FJOIN may be different to the origin of the nicks
1701                                          * in the command itself.
1702                                          */
1703                                         TreeServer* route_back_again = Utils->BestRouteTo(who->server);
1704                                         if ((!route_back_again) || (route_back_again->GetSocket() != this))
1705                                         {
1706                                                 /* Oh dear oh dear. */
1707                                                 Instance->Log(DEBUG,"Fake direction in FJOIN, user '%s'",who->nick);
1708                                                 continue;
1709                                         }
1710                                         /* Finally, we can actually place the user into the channel.
1711                                          * We're sure its right. Final answer, phone a friend.
1712                                          */
1713                                         chanrec::JoinUser(this->Instance, who, channel.c_str(), true, "");
1714
1715                                         /* Have we already queued up MAXMODES modes with parameters
1716                                          * (+qaohv) ready to be sent to the server?
1717                                          */
1718                                         if (modectr >= (MAXMODES-1))
1719                                         {
1720                                                 /* Only actually give the users any status if we lost
1721                                                  * the FJOIN or drew (equal timestamps).
1722                                                  * It isn't actually possible for ourTS to be > TS here,
1723                                                  * only possible to actually have ourTS == TS, or
1724                                                  * ourTS < TS, because if we lost, we already lowered
1725                                                  * our TS above before we entered this loop. We only
1726                                                  * check >= as a safety measure, in case someone stuffed
1727                                                  * up. If someone DID stuff up, it was most likely me.
1728                                                  * Note: I do not like baseball bats in the face...
1729                                                  */
1730                                                 if (ourTS >= TS)
1731                                                 {
1732                                                         Instance->Log(DEBUG,"Our our channel newer than theirs, accepting their modes");
1733                                                         this->Instance->SendMode((const char**)mode_users,modectr,who);
1734
1735                                                         /* Something stuffed up, and for some reason, the timestamp is
1736                                                          * NOT lowered right now and should be. Lower it. Usually this
1737                                                          * code won't be executed, doubtless someone will remove it some
1738                                                          * day soon.
1739                                                          */
1740                                                         if (ourTS > TS)
1741                                                         {
1742                                                                 Instance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",chan->name,ourTS,TS);
1743                                                                 chan->age = TS;
1744                                                                 ourTS = TS;
1745                                                         }
1746                                                 }
1747
1748                                                 /* Reset all this back to defaults, and
1749                                                  * free any ram we have left allocated.
1750                                                  */
1751                                                 strcpy(mode_users[1],"+");
1752                                                 for (unsigned int f = 2; f < modectr; f++)
1753                                                         free(mode_users[f]);
1754                                                 modectr = 2;
1755                                         }
1756                                 }
1757                                 else
1758                                 {
1759                                         /* Remember to free this */
1760                                         delete[] nm;
1761                                         /* If we got here, there's a nick in FJOIN which doesnt exist on this server.
1762                                          * We don't try to process the nickname here (that WOULD cause a segfault because
1763                                          * we'd be playing with null pointers) however, we DO pass the nickname on, just
1764                                          * in case somehow we're desynched, so that other users which might be able to see
1765                                          * the nickname get their fair chance to process it.
1766                                          */
1767                                         Instance->Log(SPARSE,"Warning! Invalid user in FJOIN to channel %s IGNORED", channel.c_str());
1768                                         continue;
1769                                 }
1770                         }
1771                 }
1772
1773                 /* there werent enough modes built up to flush it during FJOIN,
1774                  * or, there are a number left over. flush them out.
1775                  */
1776                 if ((modectr > 2) && (who) && (chan))
1777                 {
1778                         if (ourTS >= TS)
1779                         {
1780                                 /* Our channel is newer than theirs. Evil deeds must be afoot. */
1781                                 this->Instance->SendMode((const char**)mode_users,modectr,who);
1782                                 /* Yet again, we can't actually get a true value here, if everything else
1783                                  * is working as it should.
1784                                  */
1785                                 if (ourTS > TS)
1786                                 {
1787                                         Instance->Log(DEFAULT,"Channel TS for %s changed from %lu to %lu",chan->name,ourTS,TS);
1788                                         chan->age = TS;
1789                                         ourTS = TS;
1790                                 }
1791                         }
1792
1793                         /* Free anything we have left to free */
1794                         for (unsigned int f = 2; f < modectr; f++)
1795                                 free(mode_users[f]);
1796                 }
1797
1798                 /* All done. That wasnt so bad was it, you can wipe
1799                  * the sweat from your forehead now. :-)
1800                  */
1801                 return true;
1802         }
1803
1804         /** NICK command */
1805         bool IntroduceClient(const std::string &source, std::deque<std::string> &params)
1806         {
1807                 if (params.size() < 8)
1808                         return true;
1809                 if (params.size() > 8)
1810                 {
1811                         this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+params[1]+" :Invalid client introduction ("+params[1]+"?)");
1812                         return true;
1813                 }
1814                 // NICK age nick host dhost ident +modes ip :gecos
1815                 //       0    1   2     3     4      5   6     7
1816                 time_t age = atoi(params[0].c_str());
1817                 
1818                 /* This used to have a pretty craq'y loop doing the same thing,
1819                  * now we just let the STL do the hard work (more efficiently)
1820                  */
1821                 std::string::size_type pos_after_plus = params[5].find_first_not_of('+');
1822                 if (pos_after_plus != std::string::npos)
1823                         params[5] = params[5].substr(pos_after_plus);
1824                 
1825                 const char* tempnick = params[1].c_str();
1826                 Instance->Log(DEBUG,"Introduce client %s!%s@%s",tempnick,params[4].c_str(),params[2].c_str());
1827                 
1828                 user_hash::iterator iter = this->Instance->clientlist.find(tempnick);
1829                 
1830                 if (iter != this->Instance->clientlist.end())
1831                 {
1832                         // nick collision
1833                         Instance->Log(DEBUG,"Nick collision on %s!%s@%s: %lu %lu",tempnick,params[4].c_str(),params[2].c_str(),(unsigned long)age,(unsigned long)iter->second->age);
1834                         this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" KILL "+tempnick+" :Nickname collision");
1835                         userrec::QuitUser(this->Instance, iter->second, "Nickname collision");
1836                         return true;
1837                 }
1838
1839                 userrec* _new = new userrec(this->Instance);
1840                 this->Instance->clientlist[tempnick] = _new;
1841                 _new->SetFd(FD_MAGIC_NUMBER);
1842                 strlcpy(_new->nick, tempnick,NICKMAX-1);
1843                 strlcpy(_new->host, params[2].c_str(),63);
1844                 strlcpy(_new->dhost, params[3].c_str(),63);
1845                 _new->server = this->Instance->FindServerNamePtr(source.c_str());
1846                 strlcpy(_new->ident, params[4].c_str(),IDENTMAX);
1847                 strlcpy(_new->fullname, params[7].c_str(),MAXGECOS);
1848                 _new->registered = REG_ALL;
1849                 _new->signon = age;
1850                 
1851                 for (std::string::iterator v = params[5].begin(); v != params[5].end(); v++)
1852                         _new->modes[(*v)-65] = 1;
1853
1854 #ifdef SUPPORT_IP6LINKS
1855                 if (params[6].find_first_of(":") != std::string::npos)
1856                         _new->SetSockAddr(AF_INET6, params[6].c_str(), 0);
1857                 else
1858 #endif
1859                         _new->SetSockAddr(AF_INET, params[6].c_str(), 0);
1860
1861                 this->Instance->SNO->WriteToSnoMask('C',"Client connecting at %s: %s!%s@%s [%s]",_new->server,_new->nick,_new->ident,_new->host, _new->GetIPString());
1862
1863                 params[7] = ":" + params[7];
1864                 Utils->DoOneToAllButSender(source,"NICK",params,source);
1865
1866                 // Increment the Source Servers User Count..
1867                 TreeServer* SourceServer = Utils->FindServer(source);
1868                 if (SourceServer)
1869                 {
1870                         Instance->Log(DEBUG,"Found source server of %s",_new->nick);
1871                         SourceServer->AddUserCount();
1872                 }
1873
1874                 FOREACH_MOD_I(Instance,I_OnPostConnect,OnPostConnect(_new));
1875
1876                 return true;
1877         }
1878
1879         /** Send one or more FJOINs for a channel of users.
1880          * If the length of a single line is more than 480-NICKMAX
1881          * in length, it is split over multiple lines.
1882          */
1883         void SendFJoins(TreeServer* Current, chanrec* c)
1884         {
1885                 std::string buffer;
1886
1887                 Instance->Log(DEBUG,"Sending FJOINs to other server for %s",c->name);
1888                 char list[MAXBUF];
1889                 std::string individual_halfops = std::string(":")+this->Instance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age);
1890                 
1891                 size_t dlen, curlen;
1892                 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1893                 int numusers = 0;
1894                 char* ptr = list + dlen;
1895
1896                 CUList *ulist = c->GetUsers();
1897                 std::string modes = "";
1898                 std::string params = "";
1899
1900                 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1901                 {
1902                         // The first parameter gets a : before it
1903                         size_t ptrlen = snprintf(ptr, MAXBUF, " %s%s,%s", !numusers ? ":" : "", c->GetAllPrefixChars(i->second), i->second->nick);
1904
1905                         curlen += ptrlen;
1906                         ptr += ptrlen;
1907
1908                         numusers++;
1909
1910                         if (curlen > (480-NICKMAX))
1911                         {
1912                                 buffer.append(list).append("\r\n");
1913
1914                                 dlen = curlen = snprintf(list,MAXBUF,":%s FJOIN %s %lu",this->Instance->Config->ServerName,c->name,(unsigned long)c->age);
1915                                 ptr = list + dlen;
1916                                 ptrlen = 0;
1917                                 numusers = 0;
1918                         }
1919                 }
1920
1921                 if (numusers)
1922                         buffer.append(list).append("\r\n");
1923
1924                 for (BanList::iterator b = c->bans.begin(); b != c->bans.end(); b++)
1925                 {
1926                         modes.append("b");
1927                         params.append(" ").append(b->data);
1928
1929                         if (params.length() >= MAXMODES)
1930                         {
1931                                 /* Wrap at MAXMODES */
1932                                 buffer.append(":").append(this->Instance->Config->ServerName).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(modes).append(params).append("\r\n");
1933                                 modes = "";
1934                                 params = "";
1935                         }
1936                 }
1937
1938                 buffer.append(":").append(this->Instance->Config->ServerName).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(c->ChanModes(true));
1939
1940                 /* Only send these if there are any */
1941                 if (!modes.empty())
1942                         buffer.append("\r\n").append(":").append(this->Instance->Config->ServerName).append(" FMODE ").append(c->name).append(" ").append(ConvToStr(c->age)).append(" +").append(modes).append(params);
1943
1944                 this->WriteLine(buffer);
1945         }
1946
1947         /** Send G, Q, Z and E lines */
1948         void SendXLines(TreeServer* Current)
1949         {
1950                 char data[MAXBUF];
1951                 std::string buffer;
1952                 std::string n = this->Instance->Config->ServerName;
1953                 const char* sn = n.c_str();
1954                 int iterations = 0;
1955                 /* Yes, these arent too nice looking, but they get the job done */
1956                 for (std::vector<ZLine*>::iterator i = Instance->XLines->zlines.begin(); i != Instance->XLines->zlines.end(); i++, iterations++)
1957                 {
1958                         snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s\r\n",sn,(*i)->ipaddr,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
1959                         buffer.append(data);
1960                 }
1961                 for (std::vector<QLine*>::iterator i = Instance->XLines->qlines.begin(); i != Instance->XLines->qlines.end(); i++, iterations++)
1962                 {
1963                         snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s\r\n",sn,(*i)->nick,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
1964                         buffer.append(data);
1965                 }
1966                 for (std::vector<GLine*>::iterator i = Instance->XLines->glines.begin(); i != Instance->XLines->glines.end(); i++, iterations++)
1967                 {
1968                         snprintf(data,MAXBUF,":%s ADDLINE G %s@%s %s %lu %lu :%s\r\n",sn,(*i)->identmask,(*i)->hostmask,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
1969                         buffer.append(data);
1970                 }
1971                 for (std::vector<ELine*>::iterator i = Instance->XLines->elines.begin(); i != Instance->XLines->elines.end(); i++, iterations++)
1972                 {
1973                         snprintf(data,MAXBUF,":%s ADDLINE E %s@%s %s %lu %lu :%s\r\n",sn,(*i)->identmask,(*i)->hostmask,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
1974                         buffer.append(data);
1975                 }
1976                 for (std::vector<ZLine*>::iterator i = Instance->XLines->pzlines.begin(); i != Instance->XLines->pzlines.end(); i++, iterations++)
1977                 {
1978                         snprintf(data,MAXBUF,":%s ADDLINE Z %s %s %lu %lu :%s\r\n",sn,(*i)->ipaddr,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
1979                         buffer.append(data);
1980                 }
1981                 for (std::vector<QLine*>::iterator i = Instance->XLines->pqlines.begin(); i != Instance->XLines->pqlines.end(); i++, iterations++)
1982                 {
1983                         snprintf(data,MAXBUF,":%s ADDLINE Q %s %s %lu %lu :%s\r\n",sn,(*i)->nick,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
1984                         buffer.append(data);
1985                 }
1986                 for (std::vector<GLine*>::iterator i = Instance->XLines->pglines.begin(); i != Instance->XLines->pglines.end(); i++, iterations++)
1987                 {
1988                         snprintf(data,MAXBUF,":%s ADDLINE G %s@%s %s %lu %lu :%s\r\n",sn,(*i)->identmask,(*i)->hostmask,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
1989                         buffer.append(data);
1990                 }
1991                 for (std::vector<ELine*>::iterator i = Instance->XLines->pelines.begin(); i != Instance->XLines->pelines.end(); i++, iterations++)
1992                 {
1993                         snprintf(data,MAXBUF,":%s ADDLINE E %s@%s %s %lu %lu :%s\r\n",sn,(*i)->identmask,(*i)->hostmask,(*i)->source,(unsigned long)(*i)->set_time,(unsigned long)(*i)->duration,(*i)->reason);
1994                         buffer.append(data);
1995                 }
1996
1997                 if (!buffer.empty())
1998                         this->WriteLine(buffer);
1999         }
2000
2001         /** Send channel modes and topics */
2002         void SendChannelModes(TreeServer* Current)
2003         {
2004                 char data[MAXBUF];
2005                 std::deque<std::string> list;
2006                 int iterations = 0;
2007                 std::string n = this->Instance->Config->ServerName;
2008                 const char* sn = n.c_str();
2009                 for (chan_hash::iterator c = this->Instance->chanlist.begin(); c != this->Instance->chanlist.end(); c++, iterations++)
2010                 {
2011                         SendFJoins(Current, c->second);
2012                         if (*c->second->topic)
2013                         {
2014                                 snprintf(data,MAXBUF,":%s FTOPIC %s %lu %s :%s",sn,c->second->name,(unsigned long)c->second->topicset,c->second->setby,c->second->topic);
2015                                 this->WriteLine(data);
2016                         }
2017                         FOREACH_MOD_I(this->Instance,I_OnSyncChannel,OnSyncChannel(c->second,(Module*)Utils->Creator,(void*)this));
2018                         list.clear();
2019                         c->second->GetExtList(list);
2020                         for (unsigned int j = 0; j < list.size(); j++)
2021                         {
2022                                 FOREACH_MOD_I(this->Instance,I_OnSyncChannelMetaData,OnSyncChannelMetaData(c->second,(Module*)Utils->Creator,(void*)this,list[j]));
2023                         }
2024                 }
2025         }
2026
2027         /** send all users and their oper state/modes */
2028         void SendUsers(TreeServer* Current)
2029         {
2030                 char data[MAXBUF];
2031                 std::deque<std::string> list;
2032                 std::string dataline;
2033                 int iterations = 0;
2034                 for (user_hash::iterator u = this->Instance->clientlist.begin(); u != this->Instance->clientlist.end(); u++, iterations++)
2035                 {
2036                         if (u->second->registered == REG_ALL)
2037                         {
2038                                 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->FormatModes(),u->second->GetIPString(),u->second->fullname);
2039                                 this->WriteLine(data);
2040                                 if (*u->second->oper)
2041                                 {
2042                                         snprintf(data,MAXBUF,":%s OPERTYPE %s", u->second->nick, u->second->oper);
2043                                         this->WriteLine(data);
2044                                 }
2045                                 if (*u->second->awaymsg)
2046                                 {
2047                                         snprintf(data,MAXBUF,":%s AWAY :%s", u->second->nick, u->second->awaymsg);
2048                                         this->WriteLine(data);
2049                                 }
2050                                 FOREACH_MOD_I(this->Instance,I_OnSyncUser,OnSyncUser(u->second,(Module*)Utils->Creator,(void*)this));
2051                                 list.clear();
2052                                 u->second->GetExtList(list);
2053                                 for (unsigned int j = 0; j < list.size(); j++)
2054                                 {
2055                                         FOREACH_MOD_I(this->Instance,I_OnSyncUserMetaData,OnSyncUserMetaData(u->second,(Module*)Utils->Creator,(void*)this,list[j]));
2056                                 }
2057                         }
2058                 }
2059         }
2060
2061         /** This function is called when we want to send a netburst to a local
2062          * server. There is a set order we must do this, because for example
2063          * users require their servers to exist, and channels require their
2064          * users to exist. You get the idea.
2065          */
2066         void DoBurst(TreeServer* s)
2067         {
2068                 std::string burst = "BURST "+ConvToStr(Instance->Time(true));
2069                 std::string endburst = "ENDBURST";
2070                 // Because by the end of the netburst, it  could be gone!
2071                 std::string name = s->GetName();
2072                 this->Instance->SNO->WriteToSnoMask('l',"Bursting to \2"+name+"\2.");
2073                 this->WriteLine(burst);
2074                 /* send our version string */
2075                 this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" VERSION :"+this->Instance->GetVersionString());
2076                 /* Send server tree */
2077                 this->SendServers(Utils->TreeRoot,s,1);
2078                 /* Send users and their oper status */
2079                 this->SendUsers(s);
2080                 /* Send everything else (channel modes, xlines etc) */
2081                 this->SendChannelModes(s);
2082                 this->SendXLines(s);            
2083                 FOREACH_MOD_I(this->Instance,I_OnSyncOtherMetaData,OnSyncOtherMetaData((Module*)Utils->Creator,(void*)this));
2084                 this->WriteLine(endburst);
2085                 this->Instance->SNO->WriteToSnoMask('l',"Finished bursting to \2"+name+"\2.");
2086         }
2087
2088         /** This function is called when we receive data from a remote
2089          * server. We buffer the data in a std::string (it doesnt stay
2090          * there for long), reading using InspSocket::Read() which can
2091          * read up to 16 kilobytes in one operation.
2092          *
2093          * IF THIS FUNCTION RETURNS FALSE, THE CORE CLOSES AND DELETES
2094          * THE SOCKET OBJECT FOR US.
2095          */
2096         virtual bool OnDataReady()
2097         {
2098                 char* data = this->Read();
2099                 /* Check that the data read is a valid pointer and it has some content */
2100                 if (data && *data)
2101                 {
2102                         this->in_buffer.append(data);
2103                         /* While there is at least one new line in the buffer,
2104                          * do something useful (we hope!) with it.
2105                          */
2106                         while (in_buffer.find("\n") != std::string::npos)
2107                         {
2108                                 std::string ret = in_buffer.substr(0,in_buffer.find("\n")-1);
2109                                 in_buffer = in_buffer.substr(in_buffer.find("\n")+1,in_buffer.length()-in_buffer.find("\n"));
2110                                 /* Use rfind here not find, as theres more
2111                                  * chance of the \r being near the end of the
2112                                  * string, not the start.
2113                                  */
2114                                 if (ret.find("\r") != std::string::npos)
2115                                         ret = in_buffer.substr(0,in_buffer.find("\r")-1);
2116                                 /* Process this one, abort if it
2117                                  * didnt return true.
2118                                  */
2119                                 if (this->ctx_in)
2120                                 {
2121                                         char out[1024];
2122                                         char result[1024];
2123                                         memset(result,0,1024);
2124                                         memset(out,0,1024);
2125                                         /* ERROR + CAPAB is still allowed unencryped */
2126                                         if ((ret.substr(0,7) != "ERROR :") && (ret.substr(0,6) != "CAPAB "))
2127                                         {
2128                                                 int nbytes = from64tobits(out, ret.c_str(), 1024);
2129                                                 if ((nbytes > 0) && (nbytes < 1024))
2130                                                 {
2131                                                         ctx_in->Decrypt(out, result, nbytes, 0);
2132                                                         for (int t = 0; t < nbytes; t++)
2133                                                         {
2134                                                                 if (result[t] == '\7')
2135                                                                 {
2136                                                                         /* We only need to stick a \0 on the
2137                                                                          * first \7, the rest will be lost
2138                                                                          */
2139                                                                         result[t] = 0;
2140                                                                         break;
2141                                                                 }
2142                                                         }
2143                                                         ret = result;
2144                                                 }
2145                                         }
2146                                 }
2147                                 if (!this->ProcessLine(ret))
2148                                 {
2149                                         return false;
2150                                 }
2151                         }
2152                         return true;
2153                 }
2154                 /* EAGAIN returns an empty but non-NULL string, so this
2155                  * evaluates to TRUE for EAGAIN but to FALSE for EOF.
2156                  */
2157                 return (data && !*data);
2158         }
2159
2160         int WriteLine(std::string line)
2161         {
2162                 Instance->Log(DEBUG,"OUT: %s",line.c_str());
2163                 if (this->ctx_out)
2164                 {
2165                         char result[10240];
2166                         char result64[10240];
2167                         if (this->keylength)
2168                         {
2169                                 // pad it to the key length
2170                                 int n = this->keylength - (line.length() % this->keylength);
2171                                 if (n)
2172                                         line.append(n,'\7');
2173                         }
2174                         unsigned int ll = line.length();
2175                         ctx_out->Encrypt(line.c_str(), result, ll, 0);
2176                         to64frombits((unsigned char*)result64,(unsigned char*)result,ll);
2177                         line = result64;
2178                 }
2179                 line.append("\r\n");
2180                 return this->Write(line);
2181         }
2182
2183         /* Handle ERROR command */
2184         bool Error(std::deque<std::string> &params)
2185         {
2186                 if (params.size() < 1)
2187                         return false;
2188                 this->Instance->SNO->WriteToSnoMask('l',"ERROR from %s: %s",(InboundServerName != "" ? InboundServerName.c_str() : myhost.c_str()),params[0].c_str());
2189                 /* we will return false to cause the socket to close. */
2190                 return false;
2191         }
2192
2193         /** remote MOTD. leet, huh? */
2194         bool Motd(const std::string &prefix, std::deque<std::string> &params)
2195         {
2196                 if (params.size() > 0)
2197                 {
2198                         if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
2199                         {
2200                                 /* It's for our server */
2201                                 string_list results;
2202                                 userrec* source = this->Instance->FindNick(prefix);
2203
2204                                 if (source)
2205                                 {
2206                                         std::deque<std::string> par;
2207                                         par.push_back(prefix);
2208                                         par.push_back("");
2209
2210                                         if (!Instance->Config->MOTD.size())
2211                                         {
2212                                                 par[1] = std::string("::")+Instance->Config->ServerName+" 422 "+source->nick+" :Message of the day file is missing.";
2213                                                 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2214                                                 return true;
2215                                         }
2216    
2217                                         par[1] = std::string("::")+Instance->Config->ServerName+" 375 "+source->nick+" :"+Instance->Config->ServerName+" message of the day";
2218                                         Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2219    
2220                                         for (unsigned int i = 0; i < Instance->Config->MOTD.size(); i++)
2221                                         {
2222                                                 par[1] = std::string("::")+Instance->Config->ServerName+" 372 "+source->nick+" :- "+Instance->Config->MOTD[i];
2223                                                 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2224                                         }
2225      
2226                                         par[1] = std::string("::")+Instance->Config->ServerName+" 376 "+source->nick+" End of message of the day.";
2227                                         Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2228                                 }
2229                         }
2230                         else
2231                         {
2232                                 /* Pass it on */
2233                                 userrec* source = this->Instance->FindNick(prefix);
2234                                 if (source)
2235                                         Utils->DoOneToOne(prefix, "MOTD", params, params[0]);
2236                         }
2237                 }
2238                 return true;
2239         }
2240
2241         /** remote ADMIN. leet, huh? */
2242         bool Admin(const std::string &prefix, std::deque<std::string> &params)
2243         {
2244                 if (params.size() > 0)
2245                 {
2246                         if (this->Instance->MatchText(this->Instance->Config->ServerName, params[0]))
2247                         {
2248                                 /* It's for our server */
2249                                 string_list results;
2250                                 userrec* source = this->Instance->FindNick(prefix);
2251
2252                                 if (source)
2253                                 {
2254                                         std::deque<std::string> par;
2255                                         par.push_back(prefix);
2256                                         par.push_back("");
2257
2258                                         par[1] = std::string("::")+Instance->Config->ServerName+" 256 "+source->nick+" :Administrative info for "+Instance->Config->ServerName;
2259                                         Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2260
2261                                         par[1] = std::string("::")+Instance->Config->ServerName+" 257 "+source->nick+" :Name     - "+Instance->Config->AdminName;
2262                                         Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2263
2264                                         par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :Nickname - "+Instance->Config->AdminNick;
2265                                         Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2266
2267                                         par[1] = std::string("::")+Instance->Config->ServerName+" 258 "+source->nick+" :E-Mail   - "+Instance->Config->AdminEmail;
2268                                         Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2269                                 }
2270                         }
2271                         else
2272                         {
2273                                 /* Pass it on */
2274                                 userrec* source = this->Instance->FindNick(prefix);
2275                                 if (source)
2276                                         Utils->DoOneToOne(prefix, "ADMIN", params, params[0]);
2277                         }
2278                 }
2279                 return true;
2280         }
2281
2282         bool Stats(const std::string &prefix, std::deque<std::string> &params)
2283         {
2284                 /* Get the reply to a STATS query if it matches this servername,
2285                  * and send it back as a load of PUSH queries
2286                  */
2287                 if (params.size() > 1)
2288                 {
2289                         if (this->Instance->MatchText(this->Instance->Config->ServerName, params[1]))
2290                         {
2291                                 /* It's for our server */
2292                                 string_list results;
2293                                 userrec* source = this->Instance->FindNick(prefix);
2294                                 if (source)
2295                                 {
2296                                         std::deque<std::string> par;
2297                                         par.push_back(prefix);
2298                                         par.push_back("");
2299                                         DoStats(this->Instance, *(params[0].c_str()), source, results);
2300                                         for (size_t i = 0; i < results.size(); i++)
2301                                         {
2302                                                 par[1] = "::" + results[i];
2303                                                 Utils->DoOneToOne(this->Instance->Config->ServerName, "PUSH",par, source->server);
2304                                         }
2305                                 }
2306                         }
2307                         else
2308                         {
2309                                 /* Pass it on */
2310                                 userrec* source = this->Instance->FindNick(prefix);
2311                                 if (source)
2312                                         Utils->DoOneToOne(prefix, "STATS", params, params[1]);
2313                         }
2314                 }
2315                 return true;
2316         }
2317
2318
2319         /** Because the core won't let users or even SERVERS set +o,
2320          * we use the OPERTYPE command to do this.
2321          */
2322         bool OperType(const std::string &prefix, std::deque<std::string> &params)
2323         {
2324                 if (params.size() != 1)
2325                 {
2326                         Instance->Log(DEBUG,"Received invalid oper type from %s",prefix.c_str());
2327                         return true;
2328                 }
2329                 std::string opertype = params[0];
2330                 userrec* u = this->Instance->FindNick(prefix);
2331                 if (u)
2332                 {
2333                         u->modes[UM_OPERATOR] = 1;
2334                         strlcpy(u->oper,opertype.c_str(),NICKMAX-1);
2335                         Utils->DoOneToAllButSender(u->nick,"OPERTYPE",params,u->server);
2336                 }
2337                 return true;
2338         }
2339
2340         /** Because Andy insists that services-compatible servers must
2341          * implement SVSNICK and SVSJOIN, that's exactly what we do :p
2342          */
2343         bool ForceNick(const std::string &prefix, std::deque<std::string> &params)
2344         {
2345                 if (params.size() < 3)
2346                         return true;
2347
2348                 userrec* u = this->Instance->FindNick(params[0]);
2349
2350                 if (u)
2351                 {
2352                         Utils->DoOneToAllButSender(prefix,"SVSNICK",params,prefix);
2353                         if (IS_LOCAL(u))
2354                         {
2355                                 std::deque<std::string> par;
2356                                 par.push_back(params[1]);
2357                                 /* This is not required as one is sent in OnUserPostNick below
2358                                  */
2359                                 //Utils->DoOneToMany(u->nick,"NICK",par);
2360                                 if (!u->ForceNickChange(params[1].c_str()))
2361                                 {
2362                                         userrec::QuitUser(this->Instance, u, "Nickname collision");
2363                                         return true;
2364                                 }
2365                                 u->age = atoi(params[2].c_str());
2366                         }
2367                 }
2368                 return true;
2369         }
2370
2371         bool ServiceJoin(const std::string &prefix, std::deque<std::string> &params)
2372         {
2373                 if (params.size() < 2)
2374                         return true;
2375
2376                 userrec* u = this->Instance->FindNick(params[0]);
2377
2378                 if (u)
2379                 {
2380                         chanrec::JoinUser(this->Instance, u, params[1].c_str(), false);
2381                         Utils->DoOneToAllButSender(prefix,"SVSJOIN",params,prefix);
2382                 }
2383                 return true;
2384         }
2385
2386         bool RemoteRehash(const std::string &prefix, std::deque<std::string> &params)
2387         {
2388                 if (params.size() < 1)
2389                         return false;
2390
2391                 std::string servermask = params[0];
2392
2393                 if (this->Instance->MatchText(this->Instance->Config->ServerName,servermask))
2394                 {
2395                         this->Instance->SNO->WriteToSnoMask('l',"Remote rehash initiated from server \002"+prefix+"\002.");
2396                         this->Instance->RehashServer();
2397                         Utils->ReadConfiguration(false);
2398                         InitializeDisabledCommands(Instance->Config->DisabledCommands, Instance);
2399                 }
2400                 Utils->DoOneToAllButSender(prefix,"REHASH",params,prefix);
2401                 return true;
2402         }
2403
2404         bool RemoteKill(const std::string &prefix, std::deque<std::string> &params)
2405         {
2406                 if (params.size() != 2)
2407                         return true;
2408
2409                 std::string nick = params[0];
2410                 userrec* u = this->Instance->FindNick(prefix);
2411                 userrec* who = this->Instance->FindNick(nick);
2412
2413                 if (who)
2414                 {
2415                         /* Prepend kill source, if we don't have one */
2416                         std::string sourceserv = prefix;
2417                         if (u)
2418                         {
2419                                 sourceserv = u->server;
2420                         }
2421                         if (*(params[1].c_str()) != '[')
2422                         {
2423                                 params[1] = "[" + sourceserv + "] Killed (" + params[1] +")";
2424                         }
2425                         std::string reason = params[1];
2426                         params[1] = ":" + params[1];
2427                         Utils->DoOneToAllButSender(prefix,"KILL",params,sourceserv);
2428                         who->Write(":%s KILL %s :%s (%s)", sourceserv.c_str(), who->nick, sourceserv.c_str(), reason.c_str());
2429                         userrec::QuitUser(this->Instance,who,reason);
2430                 }
2431                 return true;
2432         }
2433
2434         bool LocalPong(const std::string &prefix, std::deque<std::string> &params)
2435         {
2436                 if (params.size() < 1)
2437                         return true;
2438
2439                 if (params.size() == 1)
2440                 {
2441                         TreeServer* ServerSource = Utils->FindServer(prefix);
2442                         if (ServerSource)
2443                         {
2444                                 ServerSource->SetPingFlag();
2445                         }
2446                 }
2447                 else
2448                 {
2449                         std::string forwardto = params[1];
2450                         if (forwardto == this->Instance->Config->ServerName)
2451                         {
2452                                 /*
2453                                  * this is a PONG for us
2454                                  * if the prefix is a user, check theyre local, and if they are,
2455                                  * dump the PONG reply back to their fd. If its a server, do nowt.
2456                                  * Services might want to send these s->s, but we dont need to yet.
2457                                  */
2458                                 userrec* u = this->Instance->FindNick(prefix);
2459
2460                                 if (u)
2461                                 {
2462                                         u->WriteServ("PONG %s %s",params[0].c_str(),params[1].c_str());
2463                                 }
2464                         }
2465                         else
2466                         {
2467                                 // not for us, pass it on :)
2468                                 Utils->DoOneToOne(prefix,"PONG",params,forwardto);
2469                         }
2470                 }
2471
2472                 return true;
2473         }
2474         
2475         bool MetaData(const std::string &prefix, std::deque<std::string> &params)
2476         {
2477                 if (params.size() < 3)
2478                         return true;
2479
2480                 TreeServer* ServerSource = Utils->FindServer(prefix);
2481
2482                 if (ServerSource)
2483                 {
2484                         if (params[0] == "*")
2485                         {
2486                                 FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_OTHER,NULL,params[1],params[2]));
2487                         }
2488                         else if (*(params[0].c_str()) == '#')
2489                         {
2490                                 chanrec* c = this->Instance->FindChan(params[0]);
2491                                 if (c)
2492                                 {
2493                                         FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_CHANNEL,c,params[1],params[2]));
2494                                 }
2495                         }
2496                         else if (*(params[0].c_str()) != '#')
2497                         {
2498                                 userrec* u = this->Instance->FindNick(params[0]);
2499                                 if (u)
2500                                 {
2501                                         FOREACH_MOD_I(this->Instance,I_OnDecodeMetaData,OnDecodeMetaData(TYPE_USER,u,params[1],params[2]));
2502                                 }
2503                         }
2504                 }
2505
2506                 params[2] = ":" + params[2];
2507                 Utils->DoOneToAllButSender(prefix,"METADATA",params,prefix);
2508                 return true;
2509         }
2510
2511         bool ServerVersion(const std::string &prefix, std::deque<std::string> &params)
2512         {
2513                 if (params.size() < 1)
2514                         return true;
2515
2516                 TreeServer* ServerSource = Utils->FindServer(prefix);
2517
2518                 if (ServerSource)
2519                 {
2520                         ServerSource->SetVersion(params[0]);
2521                 }
2522                 params[0] = ":" + params[0];
2523                 Utils->DoOneToAllButSender(prefix,"VERSION",params,prefix);
2524                 return true;
2525         }
2526
2527         bool ChangeHost(const std::string &prefix, std::deque<std::string> &params)
2528         {
2529                 if (params.size() < 1)
2530                         return true;
2531
2532                 userrec* u = this->Instance->FindNick(prefix);
2533
2534                 if (u)
2535                 {
2536                         u->ChangeDisplayedHost(params[0].c_str());
2537                         Utils->DoOneToAllButSender(prefix,"FHOST",params,u->server);
2538                 }
2539                 return true;
2540         }
2541
2542         bool AddLine(const std::string &prefix, std::deque<std::string> &params)
2543         {
2544                 if (params.size() < 6)
2545                         return true;
2546
2547                 bool propogate = false;
2548
2549                 switch (*(params[0].c_str()))
2550                 {
2551                         case 'Z':
2552                                 propogate = Instance->XLines->add_zline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2553                                 Instance->XLines->zline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2554                         break;
2555                         case 'Q':
2556                                 propogate = Instance->XLines->add_qline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2557                                 Instance->XLines->qline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2558                         break;
2559                         case 'E':
2560                                 propogate = Instance->XLines->add_eline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2561                                 Instance->XLines->eline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2562                         break;
2563                         case 'G':
2564                                 propogate = Instance->XLines->add_gline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2565                                 Instance->XLines->gline_set_creation_time(params[1].c_str(), atoi(params[3].c_str()));
2566                         break;
2567                         case 'K':
2568                                 propogate = Instance->XLines->add_kline(atoi(params[4].c_str()), params[2].c_str(), params[5].c_str(), params[1].c_str());
2569                         break;
2570                         default:
2571                                 /* Just in case... */
2572                                 this->Instance->SNO->WriteToSnoMask('x',"\2WARNING\2: Invalid xline type '"+params[0]+"' sent by server "+prefix+", ignored!");
2573                                 propogate = false;
2574                         break;
2575                 }
2576
2577                 /* Send it on its way */
2578                 if (propogate)
2579                 {
2580                         if (atoi(params[4].c_str()))
2581                         {
2582                                 this->Instance->SNO->WriteToSnoMask('x',"%s Added %cLINE on %s to expire in %lu seconds (%s).",prefix.c_str(),*(params[0].c_str()),params[1].c_str(),atoi(params[4].c_str()),params[5].c_str());
2583                         }
2584                         else
2585                         {
2586                                 this->Instance->SNO->WriteToSnoMask('x',"%s Added permenant %cLINE on %s (%s).",prefix.c_str(),*(params[0].c_str()),params[1].c_str(),params[5].c_str());
2587                         }
2588                         params[5] = ":" + params[5];
2589                         Utils->DoOneToAllButSender(prefix,"ADDLINE",params,prefix);
2590                 }
2591                 if (!this->bursting)
2592                 {
2593                         Instance->Log(DEBUG,"Applying lines...");
2594                         Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
2595                 }
2596                 return true;
2597         }
2598
2599         bool ChangeName(const std::string &prefix, std::deque<std::string> &params)
2600         {
2601                 if (params.size() < 1)
2602                         return true;
2603
2604                 userrec* u = this->Instance->FindNick(prefix);
2605
2606                 if (u)
2607                 {
2608                         u->ChangeName(params[0].c_str());
2609                         params[0] = ":" + params[0];
2610                         Utils->DoOneToAllButSender(prefix,"FNAME",params,u->server);
2611                 }
2612                 return true;
2613         }
2614
2615         bool Whois(const std::string &prefix, std::deque<std::string> &params)
2616         {
2617                 if (params.size() < 1)
2618                         return true;
2619
2620                 Instance->Log(DEBUG,"In IDLE command");
2621                 userrec* u = this->Instance->FindNick(prefix);
2622
2623                 if (u)
2624                 {
2625                         Instance->Log(DEBUG,"USER EXISTS: %s",u->nick);
2626                         // an incoming request
2627                         if (params.size() == 1)
2628                         {
2629                                 userrec* x = this->Instance->FindNick(params[0]);
2630                                 if ((x) && (IS_LOCAL(x)))
2631                                 {
2632                                         userrec* x = this->Instance->FindNick(params[0]);
2633                                         char signon[MAXBUF];
2634                                         char idle[MAXBUF];
2635
2636                                         snprintf(signon,MAXBUF,"%lu",(unsigned long)x->signon);
2637                                         snprintf(idle,MAXBUF,"%lu",(unsigned long)abs((x->idle_lastmsg)-Instance->Time(true)));
2638                                         std::deque<std::string> par;
2639                                         par.push_back(prefix);
2640                                         par.push_back(signon);
2641                                         par.push_back(idle);
2642                                         // ours, we're done, pass it BACK
2643                                         Utils->DoOneToOne(params[0],"IDLE",par,u->server);
2644                                 }
2645                                 else
2646                                 {
2647                                         // not ours pass it on
2648                                         Utils->DoOneToOne(prefix,"IDLE",params,x->server);
2649                                 }
2650                         }
2651                         else if (params.size() == 3)
2652                         {
2653                                 std::string who_did_the_whois = params[0];
2654                                 userrec* who_to_send_to = this->Instance->FindNick(who_did_the_whois);
2655                                 if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2656                                 {
2657                                         // an incoming reply to a whois we sent out
2658                                         std::string nick_whoised = prefix;
2659                                         unsigned long signon = atoi(params[1].c_str());
2660                                         unsigned long idle = atoi(params[2].c_str());
2661                                         if ((who_to_send_to) && (IS_LOCAL(who_to_send_to)))
2662                                                 do_whois(this->Instance,who_to_send_to,u,signon,idle,nick_whoised.c_str());
2663                                 }
2664                                 else
2665                                 {
2666                                         // not ours, pass it on
2667                                         Utils->DoOneToOne(prefix,"IDLE",params,who_to_send_to->server);
2668                                 }
2669                         }
2670                 }
2671                 return true;
2672         }
2673
2674         bool Push(const std::string &prefix, std::deque<std::string> &params)
2675         {
2676                 if (params.size() < 2)
2677                         return true;
2678
2679                 userrec* u = this->Instance->FindNick(params[0]);
2680
2681                 if (!u)
2682                         return true;
2683
2684                 if (IS_LOCAL(u))
2685                 {
2686                         u->Write(params[1]);
2687                 }
2688                 else
2689                 {
2690                         // continue the raw onwards
2691                         params[1] = ":" + params[1];
2692                         Utils->DoOneToOne(prefix,"PUSH",params,u->server);
2693                 }
2694                 return true;
2695         }
2696
2697         bool HandleSetTime(const std::string &prefix, std::deque<std::string> &params)
2698         {
2699                 if (!params.size() || !Utils->EnableTimeSync)
2700                         return true;
2701                 
2702                 bool force = false;
2703                 
2704                 if ((params.size() == 2) && (params[1] == "FORCE"))
2705                         force = true;
2706                 
2707                 time_t rts = atoi(params[0].c_str());
2708                 time_t us = Instance->Time(true);
2709                 
2710                 if (rts == us)
2711                 {
2712                         Instance->Log(DEBUG, "Timestamp from %s is equal", prefix.c_str());
2713                         
2714                         Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
2715                 }
2716                 else if (force || (rts < us))
2717                 {
2718                         int old = Instance->SetTimeDelta(rts - us);
2719                         Instance->Log(DEBUG, "%s TS (diff %d) from %s applied (old delta was %d)", (force) ? "Forced" : "Lower", rts - us, prefix.c_str(), old);
2720                         
2721                         Utils->DoOneToAllButSender(prefix, "TIMESET", params, prefix);
2722                 }
2723                 else
2724                 {
2725                         Instance->Log(DEBUG, "Higher TS (diff %d) from %s overridden", us - rts, prefix.c_str());
2726                         
2727                         std::deque<std::string> oparams;
2728                         oparams.push_back(ConvToStr(us));
2729                         
2730                         Utils->DoOneToMany(prefix, "TIMESET", oparams);
2731                 }
2732                 
2733                 return true;
2734         }
2735
2736         bool Time(const std::string &prefix, std::deque<std::string> &params)
2737         {
2738                 // :source.server TIME remote.server sendernick
2739                 // :remote.server TIME source.server sendernick TS
2740                 if (params.size() == 2)
2741                 {
2742                         // someone querying our time?
2743                         if (this->Instance->Config->ServerName == params[0])
2744                         {
2745                                 userrec* u = this->Instance->FindNick(params[1]);
2746                                 if (u)
2747                                 {
2748                                         params.push_back(ConvToStr(Instance->Time(false)));
2749                                         params[0] = prefix;
2750                                         Utils->DoOneToOne(this->Instance->Config->ServerName,"TIME",params,params[0]);
2751                                 }
2752                         }
2753                         else
2754                         {
2755                                 // not us, pass it on
2756                                 userrec* u = this->Instance->FindNick(params[1]);
2757                                 if (u)
2758                                         Utils->DoOneToOne(prefix,"TIME",params,params[0]);
2759                         }
2760                 }
2761                 else if (params.size() == 3)
2762                 {
2763                         // a response to a previous TIME
2764                         userrec* u = this->Instance->FindNick(params[1]);
2765                         if ((u) && (IS_LOCAL(u)))
2766                         {
2767                         time_t rawtime = atol(params[2].c_str());
2768                         struct tm * timeinfo;
2769                         timeinfo = localtime(&rawtime);
2770                                 char tms[26];
2771                                 snprintf(tms,26,"%s",asctime(timeinfo));
2772                                 tms[24] = 0;
2773                         u->WriteServ("391 %s %s :%s",u->nick,prefix.c_str(),tms);
2774                         }
2775                         else
2776                         {
2777                                 if (u)
2778                                         Utils->DoOneToOne(prefix,"TIME",params,u->server);
2779                         }
2780                 }
2781                 return true;
2782         }
2783         
2784         bool LocalPing(const std::string &prefix, std::deque<std::string> &params)
2785         {
2786                 if (params.size() < 1)
2787                         return true;
2788
2789                 if (params.size() == 1)
2790                 {
2791                         std::string stufftobounce = params[0];
2792                         this->WriteLine(std::string(":")+this->Instance->Config->ServerName+" PONG "+stufftobounce);
2793                         return true;
2794                 }
2795                 else
2796                 {
2797                         std::string forwardto = params[1];
2798                         if (forwardto == this->Instance->Config->ServerName)
2799                         {
2800                                 // this is a ping for us, send back PONG to the requesting server
2801                                 params[1] = params[0];
2802                                 params[0] = forwardto;
2803                                 Utils->DoOneToOne(forwardto,"PONG",params,params[1]);
2804                         }
2805                         else
2806                         {
2807                                 // not for us, pass it on :)
2808                                 Utils->DoOneToOne(prefix,"PING",params,forwardto);
2809                         }
2810                         return true;
2811                 }
2812         }
2813
2814         bool RemoveStatus(const std::string &prefix, std::deque<std::string> &params)
2815         {
2816                 if (params.size() < 1)
2817                         return true;
2818
2819                 chanrec* c = Instance->FindChan(params[0]);
2820
2821                 if (c)
2822                 {
2823                         irc::modestacker modestack(false);
2824                         CUList *ulist = c->GetUsers();
2825                         const char* y[127];
2826                         std::deque<std::string> stackresult;
2827                         std::string x;
2828
2829                         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
2830                         {
2831                                 std::string modesequence = Instance->Modes->ModeString(i->second, c);
2832                                 if (modesequence.length())
2833                                 {
2834                                         Instance->Log(DEBUG,"Mode sequence = '%s'",modesequence.c_str());
2835                                         irc::spacesepstream sep(modesequence);
2836                                         std::string modeletters = sep.GetToken();
2837                                         Instance->Log(DEBUG,"Mode letters = '%s'",modeletters.c_str());
2838                                         
2839                                         while (!modeletters.empty())
2840                                         {
2841                                                 char mletter = *(modeletters.begin());
2842                                                 modestack.Push(mletter,sep.GetToken());
2843                                                 Instance->Log(DEBUG,"Push letter = '%c'",mletter);
2844                                                 modeletters.erase(modeletters.begin());
2845                                                 Instance->Log(DEBUG,"Mode letters = '%s'",modeletters.c_str());
2846                                         }
2847                                 }
2848                         }
2849
2850                         while (modestack.GetStackedLine(stackresult))
2851                         {
2852                                 Instance->Log(DEBUG,"Stacked line size %d",stackresult.size());
2853                                 stackresult.push_front(ConvToStr(c->age));
2854                                 stackresult.push_front(c->name);
2855                                 Utils->DoOneToMany(Instance->Config->ServerName, "FMODE", stackresult);
2856                                 stackresult.erase(stackresult.begin() + 1);
2857                                 Instance->Log(DEBUG,"Stacked items:");
2858                                 for (size_t z = 0; z < stackresult.size(); z++)
2859                                 {
2860                                         y[z] = stackresult[z].c_str();
2861                                         Instance->Log(DEBUG,"\tstackresult[%d]='%s'",z,stackresult[z].c_str());
2862                                 }
2863                                 userrec* n = new userrec(Instance);
2864                                 n->SetFd(FD_MAGIC_NUMBER);
2865                                 Instance->SendMode(y, stackresult.size(), n);
2866                                 delete n;
2867                         }
2868                 }
2869                 return true;
2870         }
2871
2872         bool RemoteServer(const std::string &prefix, std::deque<std::string> &params)
2873         {
2874                 if (params.size() < 4)
2875                         return false;
2876
2877                 std::string servername = params[0];
2878                 std::string password = params[1];
2879                 // hopcount is not used for a remote server, we calculate this ourselves
2880                 std::string description = params[3];
2881                 TreeServer* ParentOfThis = Utils->FindServer(prefix);
2882
2883                 if (!ParentOfThis)
2884                 {
2885                         this->WriteLine("ERROR :Protocol error - Introduced remote server from unknown server "+prefix);
2886                         return false;
2887                 }
2888                 TreeServer* CheckDupe = Utils->FindServer(servername);
2889                 if (CheckDupe)
2890                 {
2891                         this->WriteLine("ERROR :Server "+servername+" already exists!");
2892                         this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+servername+"\2 denied, already exists");
2893                         return false;
2894                 }
2895                 TreeServer* Node = new TreeServer(this->Utils,this->Instance,servername,description,ParentOfThis,NULL);
2896                 ParentOfThis->AddChild(Node);
2897                 params[3] = ":" + params[3];
2898                 Utils->DoOneToAllButSender(prefix,"SERVER",params,prefix);
2899                 this->Instance->SNO->WriteToSnoMask('l',"Server \002"+prefix+"\002 introduced server \002"+servername+"\002 ("+description+")");
2900                 return true;
2901         }
2902
2903         bool Outbound_Reply_Server(std::deque<std::string> &params)
2904         {
2905                 if (params.size() < 4)
2906                         return false;
2907
2908                 irc::string servername = params[0].c_str();
2909                 std::string sname = params[0];
2910                 std::string password = params[1];
2911                 int hops = atoi(params[2].c_str());
2912
2913                 if (hops)
2914                 {
2915                         this->WriteLine("ERROR :Server too far away for authentication");
2916                         this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2917                         return false;
2918                 }
2919                 std::string description = params[3];
2920                 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
2921                 {
2922                         if ((x->Name == servername) && (x->RecvPass == password))
2923                         {
2924                                 TreeServer* CheckDupe = Utils->FindServer(sname);
2925                                 if (CheckDupe)
2926                                 {
2927                                         this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
2928                                         this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
2929                                         return false;
2930                                 }
2931                                 // Begin the sync here. this kickstarts the
2932                                 // other side, waiting in WAIT_AUTH_2 state,
2933                                 // into starting their burst, as it shows
2934                                 // that we're happy.
2935                                 this->LinkState = CONNECTED;
2936                                 // we should add the details of this server now
2937                                 // to the servers tree, as a child of the root
2938                                 // node.
2939                                 TreeServer* Node = new TreeServer(this->Utils,this->Instance,sname,description,Utils->TreeRoot,this);
2940                                 Utils->TreeRoot->AddChild(Node);
2941                                 params[3] = ":" + params[3];
2942                                 Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,sname);
2943                                 this->bursting = true;
2944                                 this->DoBurst(Node);
2945                                 return true;
2946                         }
2947                 }
2948                 this->WriteLine("ERROR :Invalid credentials");
2949                 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
2950                 return false;
2951         }
2952
2953         bool Inbound_Server(std::deque<std::string> &params)
2954         {
2955                 if (params.size() < 4)
2956                         return false;
2957
2958                 irc::string servername = params[0].c_str();
2959                 std::string sname = params[0];
2960                 std::string password = params[1];
2961                 int hops = atoi(params[2].c_str());
2962
2963                 if (hops)
2964                 {
2965                         this->WriteLine("ERROR :Server too far away for authentication");
2966                         this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, server is too far away for authentication");
2967                         return false;
2968                 }
2969                 std::string description = params[3];
2970                 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
2971                 {
2972                         if ((x->Name == servername) && (x->RecvPass == password))
2973                         {
2974                                 TreeServer* CheckDupe = Utils->FindServer(sname);
2975                                 if (CheckDupe)
2976                                 {
2977                                         this->WriteLine("ERROR :Server "+sname+" already exists on server "+CheckDupe->GetParent()->GetName()+"!");
2978                                         this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, already exists on server "+CheckDupe->GetParent()->GetName());
2979                                         return false;
2980                                 }
2981                                 /* If the config says this link is encrypted, but the remote side
2982                                  * hasnt bothered to send the AES command before SERVER, then we
2983                                  * boot them off as we MUST have this connection encrypted.
2984                                  */
2985                                 if ((x->EncryptionKey != "") && (!this->ctx_in))
2986                                 {
2987                                         this->WriteLine("ERROR :This link requires AES encryption to be enabled. Plaintext connection refused.");
2988                                         this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, remote server did not enable AES.");
2989                                         return false;
2990                                 }
2991                                 this->Instance->SNO->WriteToSnoMask('l',"Verified incoming server connection from \002"+sname+"\002["+(x->HiddenFromStats ? "<hidden>" : this->GetIP())+"] ("+description+")");
2992                                 this->InboundServerName = sname;
2993                                 this->InboundDescription = description;
2994                                 // this is good. Send our details: Our server name and description and hopcount of 0,
2995                                 // along with the sendpass from this block.
2996                                 this->WriteLine(std::string("SERVER ")+this->Instance->Config->ServerName+" "+x->SendPass+" 0 :"+this->Instance->Config->ServerDesc);
2997                                 // move to the next state, we are now waiting for THEM.
2998                                 this->LinkState = WAIT_AUTH_2;
2999                                 return true;
3000                         }
3001                 }
3002                 this->WriteLine("ERROR :Invalid credentials");
3003                 this->Instance->SNO->WriteToSnoMask('l',"Server connection from \2"+sname+"\2 denied, invalid link credentials");
3004                 return false;
3005         }
3006
3007         void Split(const std::string &line, std::deque<std::string> &n)
3008         {
3009                 n.clear();
3010                 irc::tokenstream tokens(line);
3011                 std::string param;
3012                 while ((param = tokens.GetToken()) != "")
3013                         n.push_back(param);
3014                 return;
3015         }
3016
3017         bool ProcessLine(std::string &line)
3018         {
3019                 std::deque<std::string> params;
3020                 irc::string command;
3021                 std::string prefix;
3022                 
3023                 if (line.empty())
3024                         return true;
3025                 
3026                 line = line.substr(0, line.find_first_of("\r\n"));
3027                 
3028                 Instance->Log(DEBUG,"IN: %s", line.c_str());
3029                 
3030                 this->Split(line.c_str(),params);
3031                         
3032                 if ((params[0][0] == ':') && (params.size() > 1))
3033                 {
3034                         prefix = params[0].substr(1);
3035                         params.pop_front();
3036                 }
3037
3038                 command = params[0].c_str();
3039                 params.pop_front();
3040
3041                 if ((!this->ctx_in) && (command == "AES"))
3042                 {
3043                         std::string sserv = params[0];
3044                         for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
3045                         {
3046                                 if ((x->EncryptionKey != "") && (x->Name == sserv))
3047                                 {
3048                                         this->InitAES(x->EncryptionKey,sserv);
3049                                 }
3050                         }
3051
3052                         return true;
3053                 }
3054                 else if ((this->ctx_in) && (command == "AES"))
3055                 {
3056                         this->Instance->SNO->WriteToSnoMask('l',"\2AES\2: Encryption already enabled on this connection yet %s is trying to enable it twice!",params[0].c_str());
3057                 }
3058
3059                 switch (this->LinkState)
3060                 {
3061                         TreeServer* Node;
3062                         
3063                         case WAIT_AUTH_1:
3064                                 // Waiting for SERVER command from remote server. Server initiating
3065                                 // the connection sends the first SERVER command, listening server
3066                                 // replies with theirs if its happy, then if the initiator is happy,
3067                                 // it starts to send its net sync, which starts the merge, otherwise
3068                                 // it sends an ERROR.
3069                                 if (command == "PASS")
3070                                 {
3071                                         /* Silently ignored */
3072                                 }
3073                                 else if (command == "SERVER")
3074                                 {
3075                                         return this->Inbound_Server(params);
3076                                 }
3077                                 else if (command == "ERROR")
3078                                 {
3079                                         return this->Error(params);
3080                                 }
3081                                 else if (command == "USER")
3082                                 {
3083                                         this->WriteLine("ERROR :Client connections to this port are prohibited.");
3084                                         return false;
3085                                 }
3086                                 else if (command == "CAPAB")
3087                                 {
3088                                         return this->Capab(params);
3089                                 }
3090                                 else if ((command == "U") || (command == "S"))
3091                                 {
3092                                         this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
3093                                         return false;
3094                                 }
3095                                 else
3096                                 {
3097                                         std::string error("ERROR :Invalid command in negotiation phase: ");
3098                                         error.append(command.c_str());
3099                                         this->WriteLine(error);
3100                                         return false;
3101                                 }
3102                         break;
3103                         case WAIT_AUTH_2:
3104                                 // Waiting for start of other side's netmerge to say they liked our
3105                                 // password.
3106                                 if (command == "SERVER")
3107                                 {
3108                                         // cant do this, they sent it to us in the WAIT_AUTH_1 state!
3109                                         // silently ignore.
3110                                         return true;
3111                                 }
3112                                 else if ((command == "U") || (command == "S"))
3113                                 {
3114                                         this->WriteLine("ERROR :Cannot use the old-style mesh linking protocol with m_spanningtree.so!");
3115                                         return false;
3116                                 }
3117                                 else if (command == "BURST")
3118                                 {
3119                                         if (params.size() && Utils->EnableTimeSync)
3120                                         {
3121                                                 /* If a time stamp is provided, apply synchronization */
3122                                                 bool force = false;
3123                                                 time_t them = atoi(params[0].c_str());
3124                                                 time_t us = Instance->Time(true);
3125                                                 int delta = them - us;
3126
3127                                                 if ((params.size() == 2) && (params[1] == "FORCE"))
3128                                                         force = true;
3129
3130                                                 if ((delta < -600) || (delta > 600))
3131                                                 {
3132                                                         this->Instance->SNO->WriteToSnoMask('l',"\2ERROR\2: Your clocks are out by %d seconds (this is more than ten minutes). Link aborted, \2PLEASE SYNC YOUR CLOCKS!\2",abs(delta));
3133                                                         this->WriteLine("ERROR :Your clocks are out by "+ConvToStr(abs(delta))+" seconds (this is more than ten minutes). Link aborted, PLEASE SYNC YOUR CLOCKS!");
3134                                                         return false;
3135                                                 }
3136                                                 
3137                                                 if (us == them)
3138                                                 {
3139                                                         this->Instance->Log(DEBUG, "Timestamps are equal; pat yourself on the back");
3140                                                 }
3141                                                 else if (force || (us > them))
3142                                                 {
3143                                                         this->Instance->Log(DEBUG, "Remote server has lower TS (%d seconds)", them - us);
3144                                                         this->Instance->SetTimeDelta(them - us);
3145                                                         // Send this new timestamp to any other servers
3146                                                         Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
3147                                                 }
3148                                                 else
3149                                                 {
3150                                                         // Override the timestamp
3151                                                         this->Instance->Log(DEBUG, "We have a higher timestamp (by %d seconds), not updating delta", us - them);
3152                                                         this->WriteLine(":" + Utils->TreeRoot->GetName() + " TIMESET " + ConvToStr(us));
3153                                                 }
3154                                         }
3155                                         this->LinkState = CONNECTED;
3156                                         Node = new TreeServer(this->Utils,this->Instance,InboundServerName,InboundDescription,Utils->TreeRoot,this);
3157                                         Utils->TreeRoot->AddChild(Node);
3158                                         params.clear();
3159                                         params.push_back(InboundServerName);
3160                                         params.push_back("*");
3161                                         params.push_back("1");
3162                                         params.push_back(":"+InboundDescription);
3163                                         Utils->DoOneToAllButSender(Utils->TreeRoot->GetName(),"SERVER",params,InboundServerName);
3164                                         this->bursting = true;
3165                                         this->DoBurst(Node);
3166                                 }
3167                                 else if (command == "ERROR")
3168                                 {
3169                                         return this->Error(params);
3170                                 }
3171                                 else if (command == "CAPAB")
3172                                 {
3173                                         return this->Capab(params);
3174                                 }
3175                                 
3176                         break;
3177                         case LISTENER:
3178                                 this->WriteLine("ERROR :Internal error -- listening socket accepted its own descriptor!!!");
3179                                 return false;
3180                         break;
3181                         case CONNECTING:
3182                                 if (command == "SERVER")
3183                                 {
3184                                         // another server we connected to, which was in WAIT_AUTH_1 state,
3185                                         // has just sent us their credentials. If we get this far, theyre
3186                                         // happy with OUR credentials, and they are now in WAIT_AUTH_2 state.
3187                                         // if we're happy with this, we should send our netburst which
3188                                         // kickstarts the merge.
3189                                         return this->Outbound_Reply_Server(params);
3190                                 }
3191                                 else if (command == "ERROR")
3192                                 {
3193                                         return this->Error(params);
3194                                 }
3195                         break;
3196                         case CONNECTED:
3197                                 // This is the 'authenticated' state, when all passwords
3198                                 // have been exchanged and anything past this point is taken
3199                                 // as gospel.
3200                                 
3201                                 if (prefix != "")
3202                                 {
3203                                         std::string direction = prefix;
3204                                         userrec* t = this->Instance->FindNick(prefix);
3205                                         if (t)
3206                                         {
3207                                                 direction = t->server;
3208                                         }
3209                                         TreeServer* route_back_again = Utils->BestRouteTo(direction);
3210                                         if ((!route_back_again) || (route_back_again->GetSocket() != this))
3211                                         {
3212                                                 if (route_back_again)
3213                                                         Instance->Log(DEBUG,"Protocol violation: Fake direction in command '%s' from connection '%s'",line.c_str(),this->GetName().c_str());
3214                                                 return true;
3215                                         }
3216
3217                                         /* Fix by brain:
3218                                          * When there is activity on the socket, reset the ping counter so
3219                                          * that we're not wasting bandwidth pinging an active server.
3220                                          */ 
3221                                         route_back_again->SetNextPingTime(time(NULL) + 60);
3222                                         route_back_again->SetPingFlag();
3223                                 }
3224                                 
3225                                 if (command == "SVSMODE")
3226                                 {
3227                                         /* Services expects us to implement
3228                                          * SVSMODE. In inspircd its the same as
3229                                          * MODE anyway.
3230                                          */
3231                                         command = "MODE";
3232                                 }
3233                                 std::string target = "";
3234                                 /* Yes, know, this is a mess. Its reasonably fast though as we're
3235                                  * working with std::string here.
3236                                  */
3237                                 if ((command == "NICK") && (params.size() > 1))
3238                                 {
3239                                         return this->IntroduceClient(prefix,params);
3240                                 }
3241                                 else if (command == "FJOIN")
3242                                 {
3243                                         return this->ForceJoin(prefix,params);
3244                                 }
3245                                 else if (command == "STATS")
3246                                 {
3247                                         return this->Stats(prefix, params);
3248                                 }
3249                                 else if (command == "MOTD")
3250                                 {
3251                                         return this->Motd(prefix, params);
3252                                 }
3253                                 else if (command == "ADMIN")
3254                                 {
3255                                         return this->Admin(prefix, params);
3256                                 }
3257                                 else if (command == "SERVER")
3258                                 {
3259                                         return this->RemoteServer(prefix,params);
3260                                 }
3261                                 else if (command == "ERROR")
3262                                 {
3263                                         return this->Error(params);
3264                                 }
3265                                 else if (command == "OPERTYPE")
3266                                 {
3267                                         return this->OperType(prefix,params);
3268                                 }
3269                                 else if (command == "FMODE")
3270                                 {
3271                                         return this->ForceMode(prefix,params);
3272                                 }
3273                                 else if (command == "KILL")
3274                                 {
3275                                         return this->RemoteKill(prefix,params);
3276                                 }
3277                                 else if (command == "FTOPIC")
3278                                 {
3279                                         return this->ForceTopic(prefix,params);
3280                                 }
3281                                 else if (command == "REHASH")
3282                                 {
3283                                         return this->RemoteRehash(prefix,params);
3284                                 }
3285                                 else if (command == "METADATA")
3286                                 {
3287                                         return this->MetaData(prefix,params);
3288                                 }
3289                                 else if (command == "REMSTATUS")
3290                                 {
3291                                         return this->RemoveStatus(prefix,params);
3292                                 }
3293                                 else if (command == "PING")
3294                                 {
3295                                         /*
3296                                          * We just got a ping from a server that's bursting.
3297                                          * This can't be right, so set them to not bursting, and
3298                                          * apply their lines.
3299                                          */
3300                                         if (this->bursting)
3301                                         {
3302                                                 this->bursting = false;
3303                                                 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3304                                         }
3305                                         if (prefix == "")
3306                                         {
3307                                                 prefix = this->GetName();
3308                                         }
3309                                         return this->LocalPing(prefix,params);
3310                                 }
3311                                 else if (command == "PONG")
3312                                 {
3313                                         /*
3314                                          * We just got a pong from a server that's bursting.
3315                                          * This can't be right, so set them to not bursting, and
3316                                          * apply their lines.
3317                                          */
3318                                         if (this->bursting)
3319                                         {
3320                                                 this->bursting = false;
3321                                                 Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3322                                         }
3323                                         if (prefix == "")
3324                                         {
3325                                                 prefix = this->GetName();
3326                                         }
3327                                         return this->LocalPong(prefix,params);
3328                                 }
3329                                 else if (command == "VERSION")
3330                                 {
3331                                         return this->ServerVersion(prefix,params);
3332                                 }
3333                                 else if (command == "FHOST")
3334                                 {
3335                                         return this->ChangeHost(prefix,params);
3336                                 }
3337                                 else if (command == "FNAME")
3338                                 {
3339                                         return this->ChangeName(prefix,params);
3340                                 }
3341                                 else if (command == "ADDLINE")
3342                                 {
3343                                         return this->AddLine(prefix,params);
3344                                 }
3345                                 else if (command == "SVSNICK")
3346                                 {
3347                                         if (prefix == "")
3348                                         {
3349                                                 prefix = this->GetName();
3350                                         }
3351                                         return this->ForceNick(prefix,params);
3352                                 }
3353                                 else if (command == "IDLE")
3354                                 {
3355                                         return this->Whois(prefix,params);
3356                                 }
3357                                 else if (command == "PUSH")
3358                                 {
3359                                         return this->Push(prefix,params);
3360                                 }
3361                                 else if (command == "TIMESET")
3362                                 {
3363                                         return this->HandleSetTime(prefix, params);
3364                                 }
3365                                 else if (command == "TIME")
3366                                 {
3367                                         return this->Time(prefix,params);
3368                                 }
3369                                 else if ((command == "KICK") && (Utils->IsServer(prefix)))
3370                                 {
3371                                         std::string sourceserv = this->myhost;
3372                                         if (params.size() == 3)
3373                                         {
3374                                                 userrec* user = this->Instance->FindNick(params[1]);
3375                                                 chanrec* chan = this->Instance->FindChan(params[0]);
3376                                                 if (user && chan)
3377                                                 {
3378                                                         if (!chan->ServerKickUser(user, params[2].c_str(), false))
3379                                                                 /* Yikes, the channels gone! */
3380                                                                 delete chan;
3381                                                 }
3382                                         }
3383                                         if (this->InboundServerName != "")
3384                                         {
3385                                                 sourceserv = this->InboundServerName;
3386                                         }
3387                                         return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3388                                 }
3389                                 else if (command == "SVSJOIN")
3390                                 {
3391                                         if (prefix == "")
3392                                         {
3393                                                 prefix = this->GetName();
3394                                         }
3395                                         return this->ServiceJoin(prefix,params);
3396                                 }
3397                                 else if (command == "SQUIT")
3398                                 {
3399                                         if (params.size() == 2)
3400                                         {
3401                                                 this->Squit(Utils->FindServer(params[0]),params[1]);
3402                                         }
3403                                         return true;
3404                                 }
3405                                 else if (command == "OPERNOTICE")
3406                                 {
3407                                         std::string sourceserv = this->myhost;
3408
3409                                         if (this->InboundServerName != "")
3410                                                 sourceserv = this->InboundServerName;
3411
3412                                         if (params.size() >= 1)
3413                                                 Instance->WriteOpers("*** From " + sourceserv + ": " + params[0]);
3414
3415                                         return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
3416                                 }
3417                                 else if (command == "MODENOTICE")
3418                                 {
3419                                         std::string sourceserv = this->myhost;
3420                                         if (this->InboundServerName != "")
3421                                                 sourceserv = this->InboundServerName;
3422                                         if (params.size() >= 2)
3423                                         {
3424                                                 Instance->WriteMode(params[0].c_str(), WM_AND, "*** From %s: %s", sourceserv.c_str(), params[1].c_str());
3425                                         }
3426
3427                                         return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
3428                                 }
3429                                 else if (command == "SNONOTICE")
3430                                 {
3431                                         std::string sourceserv = this->myhost;
3432                                         if (this->InboundServerName != "")
3433                                                 sourceserv = this->InboundServerName;
3434                                         if (params.size() >= 2)
3435                                         {
3436                                                 Instance->SNO->WriteToSnoMask(*(params[0].c_str()), "From " + sourceserv + ": "+ params[1]);
3437                                         }
3438
3439                                         return Utils->DoOneToAllButSenderRaw(line, sourceserv, prefix, command, params);
3440                                 }
3441                                 else if (command == "ENDBURST")
3442                                 {
3443                                         this->bursting = false;
3444                                         Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3445                                         std::string sourceserv = this->myhost;
3446                                         if (this->InboundServerName != "")
3447                                         {
3448                                                 sourceserv = this->InboundServerName;
3449                                         }
3450                                         this->Instance->SNO->WriteToSnoMask('l',"Received end of netburst from \2%s\2",sourceserv.c_str());
3451
3452                                         Event rmode((char*)sourceserv.c_str(), (Module*)Utils->Creator, "new_server");
3453                                         rmode.Send(Instance);
3454
3455                                         return true;
3456                                 }
3457                                 else
3458                                 {
3459                                         // not a special inter-server command.
3460                                         // Emulate the actual user doing the command,
3461                                         // this saves us having a huge ugly parser.
3462                                         userrec* who = this->Instance->FindNick(prefix);
3463                                         std::string sourceserv = this->myhost;
3464                                         if (this->InboundServerName != "")
3465                                         {
3466                                                 sourceserv = this->InboundServerName;
3467                                         }
3468                                         if ((!who) && (command == "MODE"))
3469                                         {
3470                                                 if (Utils->IsServer(prefix))
3471                                                 {
3472                                                         const char* modelist[127];
3473                                                         for (size_t i = 0; i < params.size(); i++)
3474                                                                 modelist[i] = params[i].c_str();
3475
3476                                                         userrec* fake = new userrec(Instance);
3477                                                         fake->SetFd(FD_MAGIC_NUMBER);
3478
3479                                                         this->Instance->SendMode(modelist, params.size(), fake);
3480         
3481                                                         delete fake;
3482
3483                                                         /* Hot potato! pass it on! */
3484                                                         return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3485                                                 }
3486                                         }
3487                                         if (who)
3488                                         {
3489                                                 if ((command == "NICK") && (params.size() > 0))
3490                                                 {
3491                                                         /* On nick messages, check that the nick doesnt
3492                                                          * already exist here. If it does, kill their copy,
3493                                                          * and our copy.
3494                                                          */
3495                                                         userrec* x = this->Instance->FindNick(params[0]);
3496                                                         if ((x) && (x != who))
3497                                                         {
3498                                                                 std::deque<std::string> p;
3499                                                                 p.push_back(params[0]);
3500                                                                 p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
3501                                                                 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
3502                                                                 p.clear();
3503                                                                 p.push_back(prefix);
3504                                                                 p.push_back("Nickname collision");
3505                                                                 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
3506                                                                 userrec::QuitUser(this->Instance,x,"Nickname collision ("+prefix+" -> "+params[0]+")");
3507                                                                 userrec* y = this->Instance->FindNick(prefix);
3508                                                                 if (y)
3509                                                                 {
3510                                                                         userrec::QuitUser(this->Instance,y,"Nickname collision");
3511                                                                 }
3512                                                                 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3513                                                         }
3514                                                 }
3515                                                 // its a user
3516                                                 target = who->server;
3517                                                 const char* strparams[127];
3518                                                 for (unsigned int q = 0; q < params.size(); q++)
3519                                                 {
3520                                                         strparams[q] = params[q].c_str();
3521                                                 }
3522                                                 switch (this->Instance->CallCommandHandler(command.c_str(), strparams, params.size(), who))
3523                                                 {
3524                                                         case CMD_INVALID:
3525                                                                 this->WriteLine("ERROR :Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
3526                                                                 return false;
3527                                                         break;
3528                                                         case CMD_FAILURE:
3529                                                                 return true;
3530                                                         break;
3531                                                         default:
3532                                                                 /* CMD_SUCCESS and CMD_USER_DELETED fall through here */
3533                                                         break;
3534                                                 }
3535                                         }
3536                                         else
3537                                         {
3538                                                 // its not a user. Its either a server, or somethings screwed up.
3539                                                 if (Utils->IsServer(prefix))
3540                                                 {
3541                                                         target = this->Instance->Config->ServerName;
3542                                                 }
3543                                                 else
3544                                                 {
3545                                                         Instance->Log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
3546                                                         return true;
3547                                                 }
3548                                         }
3549                                         return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3550
3551                                 }
3552                                 return true;
3553                         break;
3554                 }
3555                 return true;
3556         }
3557
3558         virtual std::string GetName()
3559         {
3560                 std::string sourceserv = this->myhost;
3561                 if (this->InboundServerName != "")
3562                 {
3563                         sourceserv = this->InboundServerName;
3564                 }
3565                 return sourceserv;
3566         }
3567
3568         virtual void OnTimeout()
3569         {
3570                 if (this->LinkState == CONNECTING)
3571                 {
3572                         this->Instance->SNO->WriteToSnoMask('l',"CONNECT: Connection to \002"+myhost+"\002 timed out.");
3573                         Link* MyLink = Utils->FindLink(myhost);
3574                         if (MyLink)
3575                                 Utils->DoFailOver(MyLink);
3576                 }
3577         }
3578
3579         virtual void OnClose()
3580         {
3581                 // Connection closed.
3582                 // If the connection is fully up (state CONNECTED)
3583                 // then propogate a netsplit to all peers.
3584                 std::string quitserver = this->myhost;
3585                 if (this->InboundServerName != "")
3586                 {
3587                         quitserver = this->InboundServerName;
3588                 }
3589                 TreeServer* s = Utils->FindServer(quitserver);
3590                 if (s)
3591                 {
3592                         Squit(s,"Remote host closed the connection");
3593                 }
3594
3595                 if (quitserver != "")
3596                         this->Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' failed.",quitserver.c_str());
3597         }
3598
3599         virtual int OnIncomingConnection(int newsock, char* ip)
3600         {
3601                 /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
3602                  * or discovering if this port is the server port, we don't allow connections from any
3603                  * IPs for which we don't have a link block.
3604                  */
3605                 bool found = false;
3606
3607                 found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());
3608                 if (!found)
3609                 {
3610                         for (vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
3611                                 if (irc::sockets::MatchCIDR(ip, (*i).c_str()))
3612                                         found = true;
3613
3614                         if (!found)
3615                         {
3616                                 this->Instance->SNO->WriteToSnoMask('l',"Server connection from %s denied (no link blocks with that IP address)", ip);
3617                                 close(newsock);
3618                                 return false;
3619                         }
3620                 }
3621                 TreeSocket* s = new TreeSocket(this->Utils, this->Instance, newsock, ip);
3622                 s = s; /* Whinge whinge whinge, thats all GCC ever does. */
3623                 return true;
3624         }
3625 };
3626
3627 /** This class is used to resolve server hostnames during /connect and autoconnect.
3628  * As of 1.1, the resolver system is seperated out from InspSocket, so we must do this
3629  * resolver step first ourselves if we need it. This is totally nonblocking, and will
3630  * callback to OnLookupComplete or OnError when completed. Once it has completed we
3631  * will have an IP address which we can then use to continue our connection.
3632  */
3633 class ServernameResolver : public Resolver
3634 {       
3635  private:
3636         /** A copy of the Link tag info for what we're connecting to.
3637          * We take a copy, rather than using a pointer, just in case the
3638          * admin takes the tag away and rehashes while the domain is resolving.
3639          */
3640         Link MyLink;
3641         SpanningTreeUtilities* Utils;
3642  public: 
3643         ServernameResolver(Module* me, SpanningTreeUtilities* Util, InspIRCd* Instance, const std::string &hostname, Link x) : Resolver(Instance, hostname, DNS_QUERY_FORWARD, me), MyLink(x), Utils(Util)
3644         {
3645                 /* Nothing in here, folks */
3646         }
3647
3648         void OnLookupComplete(const std::string &result)
3649         {
3650                 /* Initiate the connection, now that we have an IP to use.
3651                  * Passing a hostname directly to InspSocket causes it to
3652                  * just bail and set its FD to -1.
3653                  */
3654                 TreeServer* CheckDupe = Utils->FindServer(MyLink.Name.c_str());
3655                 if (!CheckDupe) /* Check that nobody tried to connect it successfully while we were resolving */
3656                 {
3657                         TreeSocket* newsocket = new TreeSocket(this->Utils, ServerInstance, result,MyLink.Port,false,MyLink.Timeout ? MyLink.Timeout : 10,MyLink.Name.c_str());
3658                         if (newsocket->GetFd() > -1)
3659                         {
3660                                 /* We're all OK */
3661                         }
3662                         else
3663                         {
3664                                 /* Something barfed, show the opers */
3665                                 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",MyLink.Name.c_str(),strerror(errno));
3666                                 delete newsocket;
3667                                 Utils->DoFailOver(&MyLink);
3668                         }
3669                 }
3670         }
3671
3672         void OnError(ResolverError e, const std::string &errormessage)
3673         {
3674                 /* Ooops! */
3675                 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: Unable to resolve hostname - %s",MyLink.Name.c_str(),errormessage.c_str());
3676                 Utils->DoFailOver(&MyLink);
3677         }
3678 };
3679
3680 /** Handle resolving of server IPs for the cache
3681  */
3682 class SecurityIPResolver : public Resolver
3683 {
3684  private:
3685         Link MyLink;
3686         SpanningTreeUtilities* Utils;
3687  public:
3688         SecurityIPResolver(Module* me, SpanningTreeUtilities* U, InspIRCd* Instance, const std::string &hostname, Link x) : Resolver(Instance, hostname, DNS_QUERY_FORWARD, me), MyLink(x), Utils(U)
3689         {
3690         }
3691
3692         void OnLookupComplete(const std::string &result)
3693         {
3694                 ServerInstance->Log(DEBUG,"Security IP cache: Adding IP address '%s' for Link '%s'",result.c_str(),MyLink.Name.c_str());
3695                 Utils->ValidIPs.push_back(result);
3696         }
3697
3698         void OnError(ResolverError e, const std::string &errormessage)
3699         {
3700                 ServerInstance->Log(DEBUG,"Could not resolve IP associated with Link '%s': %s",MyLink.Name.c_str(),errormessage.c_str());
3701         }
3702 };
3703
3704 SpanningTreeUtilities::SpanningTreeUtilities(InspIRCd* Instance, ModuleSpanningTree* C) : ServerInstance(Instance), Creator(C)
3705 {
3706         Bindings.clear();
3707         this->ReadConfiguration(true);
3708         this->TreeRoot = new TreeServer(this, ServerInstance, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc);
3709 }
3710
3711 SpanningTreeUtilities::~SpanningTreeUtilities()
3712 {
3713         for (unsigned int i = 0; i < Bindings.size(); i++)
3714         {
3715                 ServerInstance->Log(DEBUG,"Freeing binding %d of %d",i, Bindings.size());
3716                 ServerInstance->SE->DelFd(Bindings[i]);
3717                 Bindings[i]->Close();
3718                 DELETE(Bindings[i]);
3719         }
3720         ServerInstance->Log(DEBUG,"Freeing connected servers...");
3721         while (TreeRoot->ChildCount())
3722         {
3723                 TreeServer* child_server = TreeRoot->GetChild(0);
3724                 ServerInstance->Log(DEBUG,"Freeing connected server %s", child_server->GetName().c_str());
3725                 if (child_server)
3726                 {
3727                         TreeSocket* sock = child_server->GetSocket();
3728                         ServerInstance->SE->DelFd(sock);
3729                         sock->Close();
3730                         DELETE(sock);
3731                 }
3732         }
3733         delete TreeRoot;
3734 }
3735
3736 void SpanningTreeUtilities::AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
3737 {
3738         for (unsigned int c = 0; c < list.size(); c++)
3739         {
3740                 if (list[c] == server)
3741                 {
3742                         return;
3743                 }
3744         }
3745         list.push_back(server);
3746 }
3747
3748 /** returns a list of DIRECT servernames for a specific channel */
3749 void SpanningTreeUtilities::GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
3750 {
3751         CUList *ulist = c->GetUsers();
3752         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
3753         {
3754                 if (i->second->GetFd() < 0)
3755                 {
3756                         TreeServer* best = this->BestRouteTo(i->second->server);
3757                         if (best)
3758                                 AddThisServer(best,list);
3759                 }
3760         }
3761         return;
3762 }
3763
3764 bool SpanningTreeUtilities::DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, std::deque<std::string> &params)
3765 {
3766         TreeServer* omitroute = this->BestRouteTo(omit);
3767         if ((command == "NOTICE") || (command == "PRIVMSG"))
3768         {
3769                 if (params.size() >= 2)
3770                 {
3771                         /* Prefixes */
3772                         if ((*(params[0].c_str()) == '@') || (*(params[0].c_str()) == '%') || (*(params[0].c_str()) == '+'))
3773                         {
3774                                 params[0] = params[0].substr(1, params[0].length()-1);
3775                         }
3776                         if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$'))
3777                         {
3778                                 // special routing for private messages/notices
3779                                 userrec* d = ServerInstance->FindNick(params[0]);
3780                                 if (d)
3781                                 {
3782                                         std::deque<std::string> par;
3783                                         par.push_back(params[0]);
3784                                         par.push_back(":"+params[1]);
3785                                         this->DoOneToOne(prefix,command.c_str(),par,d->server);
3786                                         return true;
3787                                 }
3788                         }
3789                         else if (*(params[0].c_str()) == '$')
3790                         {
3791                                 std::deque<std::string> par;
3792                                 par.push_back(params[0]);
3793                                 par.push_back(":"+params[1]);
3794                                 this->DoOneToAllButSender(prefix,command.c_str(),par,omitroute->GetName());
3795                                 return true;
3796                         }
3797                         else
3798                         {
3799                                 chanrec* c = ServerInstance->FindChan(params[0]);
3800                                 if (c)
3801                                 {
3802                                         std::deque<TreeServer*> list;
3803                                         GetListOfServersForChannel(c,list);
3804                                         unsigned int lsize = list.size();
3805                                         for (unsigned int i = 0; i < lsize; i++)
3806                                         {
3807                                                 TreeSocket* Sock = list[i]->GetSocket();
3808                                                 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
3809                                                 {
3810                                                         Sock->WriteLine(data);
3811                                                 }
3812                                         }
3813                                         return true;
3814                                 }
3815                         }
3816                 }
3817         }
3818         unsigned int items =this->TreeRoot->ChildCount();
3819         for (unsigned int x = 0; x < items; x++)
3820         {
3821                 TreeServer* Route = this->TreeRoot->GetChild(x);
3822                 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3823                 {
3824                         TreeSocket* Sock = Route->GetSocket();
3825                         if (Sock)
3826                                 Sock->WriteLine(data);
3827                 }
3828         }
3829         return true;
3830 }
3831
3832 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, std::deque<std::string> &params, std::string omit)
3833 {
3834         TreeServer* omitroute = this->BestRouteTo(omit);
3835         std::string FullLine = ":" + prefix + " " + command;
3836         unsigned int words = params.size();
3837         for (unsigned int x = 0; x < words; x++)
3838         {
3839                 FullLine = FullLine + " " + params[x];
3840         }
3841         unsigned int items = this->TreeRoot->ChildCount();
3842         for (unsigned int x = 0; x < items; x++)
3843         {
3844                 TreeServer* Route = this->TreeRoot->GetChild(x);
3845                 // Send the line IF:
3846                 // The route has a socket (its a direct connection)
3847                 // The route isnt the one to be omitted
3848                 // The route isnt the path to the one to be omitted
3849                 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3850                 {
3851                         TreeSocket* Sock = Route->GetSocket();
3852                         if (Sock)
3853                                 Sock->WriteLine(FullLine);
3854                 }
3855         }
3856         return true;
3857 }
3858
3859 bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, std::deque<std::string> &params)
3860 {
3861         std::string FullLine = ":" + prefix + " " + command;
3862         unsigned int words = params.size();
3863         for (unsigned int x = 0; x < words; x++)
3864         {
3865                 FullLine = FullLine + " " + params[x];
3866         }
3867         unsigned int items = this->TreeRoot->ChildCount();
3868         for (unsigned int x = 0; x < items; x++)
3869         {
3870                 TreeServer* Route = this->TreeRoot->GetChild(x);
3871                 if (Route && Route->GetSocket())
3872                 {
3873                         TreeSocket* Sock = Route->GetSocket();
3874                         if (Sock)
3875                                 Sock->WriteLine(FullLine);
3876                 }
3877         }
3878         return true;
3879 }
3880
3881 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, std::deque<std::string> &params)
3882 {
3883         std::string spfx = prefix;
3884         std::string scmd = command;
3885         return this->DoOneToMany(spfx, scmd, params);
3886 }
3887
3888 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> &params, std::string omit)
3889 {
3890         std::string spfx = prefix;
3891         std::string scmd = command;
3892         return this->DoOneToAllButSender(spfx, scmd, params, omit);
3893 }
3894         
3895 bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, std::deque<std::string> &params, std::string target)
3896 {
3897         TreeServer* Route = this->BestRouteTo(target);
3898         if (Route)
3899         {
3900                 std::string FullLine = ":" + prefix + " " + command;
3901                 unsigned int words = params.size();
3902                 for (unsigned int x = 0; x < words; x++)
3903                 {
3904                         FullLine = FullLine + " " + params[x];
3905                 }
3906                 if (Route && Route->GetSocket())
3907                 {
3908                         TreeSocket* Sock = Route->GetSocket();
3909                         if (Sock)
3910                                 Sock->WriteLine(FullLine);
3911                 }
3912                 return true;
3913         }
3914         else
3915         {
3916                 return false;
3917         }
3918 }
3919
3920 void SpanningTreeUtilities::ReadConfiguration(bool rebind)
3921 {
3922         ConfigReader* Conf = new ConfigReader(ServerInstance);
3923         if (rebind)
3924         {
3925                 for (int j =0; j < Conf->Enumerate("bind"); j++)
3926                 {
3927                         std::string Type = Conf->ReadValue("bind","type",j);
3928                         std::string IP = Conf->ReadValue("bind","address",j);
3929                         std::string Port = Conf->ReadValue("bind","port",j);
3930                         if (Type == "servers")
3931                         {
3932                                 irc::portparser portrange(Port, false);
3933                                 int portno = -1;
3934                                 while ((portno = portrange.GetToken()))
3935                                 {
3936                                         ServerInstance->Log(DEBUG,"m_spanningtree: Binding server port %s:%d", IP.c_str(), portno);
3937                                         if (IP == "*")
3938                                                 IP = "";
3939
3940                                         TreeSocket* listener = new TreeSocket(this, ServerInstance, IP.c_str(), portno, true, 10);
3941                                         if (listener->GetState() == I_LISTENING)
3942                                         {
3943                                                 ServerInstance->Log(DEFAULT,"m_spanningtree: Binding server port %s:%d successful!", IP.c_str(), portno);
3944                                                 Bindings.push_back(listener);
3945                                         }
3946                                         else
3947                                         {
3948                                                 ServerInstance->Log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %s:%d",IP.c_str(), portno);
3949                                                 listener->Close();
3950                                                 DELETE(listener);
3951                                         }
3952                                         ServerInstance->Log(DEBUG,"Done with this binding");
3953                                 }
3954                         }
3955                 }
3956         }
3957         FlatLinks = Conf->ReadFlag("options","flatlinks",0);
3958         HideULines = Conf->ReadFlag("options","hideulines",0);
3959         AnnounceTSChange = Conf->ReadFlag("options","announcets",0);
3960         EnableTimeSync = !(Conf->ReadFlag("options","notimesync",0));
3961         LinkBlocks.clear();
3962         ValidIPs.clear();
3963         for (int j =0; j < Conf->Enumerate("link"); j++)
3964         {
3965                 Link L;
3966                 std::string Allow = Conf->ReadValue("link","allowmask",j);
3967                 L.Name = (Conf->ReadValue("link","name",j)).c_str();
3968                 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
3969                 L.FailOver = Conf->ReadValue("link","failover",j).c_str();
3970                 L.Port = Conf->ReadInteger("link","port",j,true);
3971                 L.SendPass = Conf->ReadValue("link","sendpass",j);
3972                 L.RecvPass = Conf->ReadValue("link","recvpass",j);
3973                 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
3974                 L.EncryptionKey =  Conf->ReadValue("link","encryptionkey",j);
3975                 L.HiddenFromStats = Conf->ReadFlag("link","hidden",j);
3976                 L.Timeout = Conf->ReadInteger("link","timeout",j,true);
3977                 L.NextConnectTime = time(NULL) + L.AutoConnect;
3978                 /* Bugfix by brain, do not allow people to enter bad configurations */
3979                 if (L.Name != ServerInstance->Config->ServerName)
3980                 {
3981                         if ((L.IPAddr != "") && (L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
3982                         {
3983                                 ValidIPs.push_back(L.IPAddr);
3984
3985                                 if (Allow.length())
3986                                         ValidIPs.push_back(Allow);
3987
3988                                 /* Needs resolving */
3989                                 insp_inaddr binip;
3990                                 if (insp_aton(L.IPAddr.c_str(), &binip) < 1)
3991                                 {
3992                                         try
3993                                         {
3994                                                 SecurityIPResolver* sr = new SecurityIPResolver((Module*)this->Creator, this, ServerInstance, L.IPAddr, L);
3995                                                 ServerInstance->AddResolver(sr);
3996                                         }
3997                                         catch (ModuleException& e)
3998                                         {
3999                                                 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
4000                                         }
4001                                 }
4002
4003                                 LinkBlocks.push_back(L);
4004                                 ServerInstance->Log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
4005                         }
4006                         else
4007                         {
4008                                 if (L.IPAddr == "")
4009                                 {
4010                                         ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', IP address not defined!",L.Name.c_str());
4011                                 }
4012                                 else if (L.RecvPass == "")
4013                                 {
4014                                         ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', recvpass not defined!",L.Name.c_str());
4015                                 }
4016                                 else if (L.SendPass == "")
4017                                 {
4018                                         ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', sendpass not defined!",L.Name.c_str());
4019                                 }
4020                                 else if (L.Name == "")
4021                                 {
4022                                         ServerInstance->Log(DEFAULT,"Invalid configuration, link tag without a name!");
4023                                 }
4024                                 else if (!L.Port)
4025                                 {
4026                                         ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', no port specified!",L.Name.c_str());
4027                                 }
4028                         }
4029                 }
4030                 else
4031                 {
4032                         ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', link tag has the same server name as the local server!",L.Name.c_str());
4033                 }
4034         }
4035         DELETE(Conf);
4036 }
4037
4038 /** To create a timer which recurs every second, we inherit from InspTimer.
4039  * InspTimer is only one-shot however, so at the end of each Tick() we simply
4040  * insert another of ourselves into the pending queue :)
4041  */
4042 class TimeSyncTimer : public InspTimer
4043 {
4044  private:
4045         InspIRCd *Instance;
4046         ModuleSpanningTree *Module;
4047  public:
4048         TimeSyncTimer(InspIRCd *Instance, ModuleSpanningTree *Mod);
4049         virtual void Tick(time_t TIME);
4050 };
4051
4052 class ModuleSpanningTree : public Module
4053 {
4054         int line;
4055         int NumServers;
4056         unsigned int max_local;
4057         unsigned int max_global;
4058         cmd_rconnect* command_rconnect;
4059         SpanningTreeUtilities* Utils;
4060
4061  public:
4062         TimeSyncTimer *SyncTimer;
4063
4064         ModuleSpanningTree(InspIRCd* Me)
4065                 : Module::Module(Me), max_local(0), max_global(0)
4066         {
4067                 Utils = new SpanningTreeUtilities(Me, this);
4068
4069                 command_rconnect = new cmd_rconnect(ServerInstance, this, Utils);
4070                 ServerInstance->AddCommand(command_rconnect);
4071
4072                 if (Utils->EnableTimeSync)
4073                 {
4074                         SyncTimer = new TimeSyncTimer(ServerInstance, this);
4075                         ServerInstance->Timers->AddTimer(SyncTimer);
4076                 }
4077                 else
4078                         SyncTimer = NULL;
4079         }
4080
4081         void ShowLinks(TreeServer* Current, userrec* user, int hops)
4082         {
4083                 std::string Parent = Utils->TreeRoot->GetName();
4084                 if (Current->GetParent())
4085                 {
4086                         Parent = Current->GetParent()->GetName();
4087                 }
4088                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
4089                 {
4090                         if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str())))
4091                         {
4092                                 if (*user->oper)
4093                                 {
4094                                          ShowLinks(Current->GetChild(q),user,hops+1);
4095                                 }
4096                         }
4097                         else
4098                         {
4099                                 ShowLinks(Current->GetChild(q),user,hops+1);
4100                         }
4101                 }
4102                 /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
4103                 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetName().c_str())) && (!*user->oper))
4104                         return;
4105                 user->WriteServ("364 %s %s %s :%d %s",user->nick,Current->GetName().c_str(),(Utils->FlatLinks && (!*user->oper)) ? ServerInstance->Config->ServerName : Parent.c_str(),(Utils->FlatLinks && (!*user->oper)) ? 0 : hops,Current->GetDesc().c_str());
4106         }
4107
4108         int CountLocalServs()
4109         {
4110                 return Utils->TreeRoot->ChildCount();
4111         }
4112
4113         int CountServs()
4114         {
4115                 return Utils->serverlist.size();
4116         }
4117
4118         void HandleLinks(const char** parameters, int pcnt, userrec* user)
4119         {
4120                 ShowLinks(Utils->TreeRoot,user,0);
4121                 user->WriteServ("365 %s * :End of /LINKS list.",user->nick);
4122                 return;
4123         }
4124
4125         void HandleLusers(const char** parameters, int pcnt, userrec* user)
4126         {
4127                 unsigned int n_users = ServerInstance->UserCount();
4128
4129                 /* Only update these when someone wants to see them, more efficient */
4130                 if ((unsigned int)ServerInstance->LocalUserCount() > max_local)
4131                         max_local = ServerInstance->LocalUserCount();
4132                 if (n_users > max_global)
4133                         max_global = n_users;
4134
4135                 user->WriteServ("251 %s :There are %d users and %d invisible on %d servers",user->nick,n_users-ServerInstance->InvisibleUserCount(),ServerInstance->InvisibleUserCount(),this->CountServs());
4136                 if (ServerInstance->OperCount())
4137                         user->WriteServ("252 %s %d :operator(s) online",user->nick,ServerInstance->OperCount());
4138                 if (ServerInstance->UnregisteredUserCount())
4139                         user->WriteServ("253 %s %d :unknown connections",user->nick,ServerInstance->UnregisteredUserCount());
4140                 if (ServerInstance->ChannelCount())
4141                         user->WriteServ("254 %s %d :channels formed",user->nick,ServerInstance->ChannelCount());
4142                 user->WriteServ("254 %s :I have %d clients and %d servers",user->nick,ServerInstance->LocalUserCount(),this->CountLocalServs());
4143                 user->WriteServ("265 %s :Current Local Users: %d  Max: %d",user->nick,ServerInstance->LocalUserCount(),max_local);
4144                 user->WriteServ("266 %s :Current Global Users: %d  Max: %d",user->nick,n_users,max_global);
4145                 return;
4146         }
4147
4148         // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
4149
4150         void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80], float &totusers, float &totservers)
4151         {
4152                 if (line < 128)
4153                 {
4154                         for (int t = 0; t < depth; t++)
4155                         {
4156                                 matrix[line][t] = ' ';
4157                         }
4158
4159                         // For Aligning, we need to work out exactly how deep this thing is, and produce
4160                         // a 'Spacer' String to compensate.
4161                         char spacer[40];
4162
4163                         memset(spacer,' ',40);
4164                         if ((40 - Current->GetName().length() - depth) > 1) {
4165                                 spacer[40 - Current->GetName().length() - depth] = '\0';
4166                         }
4167                         else
4168                         {
4169                                 spacer[5] = '\0';
4170                         }
4171
4172                         float percent;
4173                         char text[80];
4174                         if (ServerInstance->clientlist.size() == 0) {
4175                                 // If there are no users, WHO THE HELL DID THE /MAP?!?!?!
4176                                 percent = 0;
4177                         }
4178                         else
4179                         {
4180                                 percent = ((float)Current->GetUserCount() / (float)ServerInstance->clientlist.size()) * 100;
4181                         }
4182                         snprintf(text, 80, "%s %s%5d [%5.2f%%]", Current->GetName().c_str(), spacer, Current->GetUserCount(), percent);
4183                         totusers += Current->GetUserCount();
4184                         totservers++;
4185                         strlcpy(&matrix[line][depth],text,80);
4186                         line++;
4187                         for (unsigned int q = 0; q < Current->ChildCount(); q++)
4188                         {
4189                                 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str())))
4190                                 {
4191                                         if (*user->oper)
4192                                         {
4193                                                 ShowMap(Current->GetChild(q),user,(Utils->FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
4194                                         }
4195                                 }
4196                                 else
4197                                 {
4198                                         ShowMap(Current->GetChild(q),user,(Utils->FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
4199                                 }
4200                         }
4201                 }
4202         }
4203
4204         int HandleMotd(const char** parameters, int pcnt, userrec* user)
4205         {
4206                 if (pcnt > 0)
4207                 {
4208                         /* Remote MOTD, the server is within the 1st parameter */
4209                         std::deque<std::string> params;
4210                         params.push_back(parameters[0]);
4211
4212                         /* Send it out remotely, generate no reply yet */
4213                         TreeServer* s = Utils->FindServerMask(parameters[0]);
4214                         if (s)
4215                         {
4216                                 Utils->DoOneToOne(user->nick, "MOTD", params, s->GetName());
4217                         }
4218                         else
4219                         {
4220                                 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4221                         }
4222                         return 1;
4223                 }
4224                 return 0;
4225         }
4226
4227         int HandleAdmin(const char** parameters, int pcnt, userrec* user)
4228         {
4229                 if (pcnt > 0)
4230                 {
4231                         /* Remote ADMIN, the server is within the 1st parameter */
4232                         std::deque<std::string> params;
4233                         params.push_back(parameters[0]);
4234
4235                         /* Send it out remotely, generate no reply yet */
4236                         TreeServer* s = Utils->FindServerMask(parameters[0]);
4237                         if (s)
4238                         {
4239                                 Utils->DoOneToOne(user->nick, "ADMIN", params, s->GetName());
4240                         }
4241                         else
4242                         {
4243                                 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4244                         }
4245                         return 1;
4246                 }
4247                 return 0;
4248         }
4249
4250         int HandleStats(const char** parameters, int pcnt, userrec* user)
4251         {
4252                 if (pcnt > 1)
4253                 {
4254                         /* Remote STATS, the server is within the 2nd parameter */
4255                         std::deque<std::string> params;
4256                         params.push_back(parameters[0]);
4257                         params.push_back(parameters[1]);
4258                         /* Send it out remotely, generate no reply yet */
4259                         TreeServer* s = Utils->FindServerMask(parameters[1]);
4260                         if (s)
4261                         {
4262                                 params[1] = s->GetName();
4263                                 Utils->DoOneToOne(user->nick, "STATS", params, s->GetName());
4264                         }
4265                         else
4266                         {
4267                                 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4268                         }
4269                         return 1;
4270                 }
4271                 return 0;
4272         }
4273
4274         // Ok, prepare to be confused.
4275         // After much mulling over how to approach this, it struck me that
4276         // the 'usual' way of doing a /MAP isnt the best way. Instead of
4277         // keeping track of a ton of ascii characters, and line by line
4278         // under recursion working out where to place them using multiplications
4279         // and divisons, we instead render the map onto a backplane of characters
4280         // (a character matrix), then draw the branches as a series of "L" shapes
4281         // from the nodes. This is not only friendlier on CPU it uses less stack.
4282
4283         void HandleMap(const char** parameters, int pcnt, userrec* user)
4284         {
4285                 // This array represents a virtual screen which we will
4286                 // "scratch" draw to, as the console device of an irc
4287                 // client does not provide for a proper terminal.
4288                 float totusers = 0;
4289                 float totservers = 0;
4290                 char matrix[128][80];
4291                 for (unsigned int t = 0; t < 128; t++)
4292                 {
4293                         matrix[t][0] = '\0';
4294                 }
4295                 line = 0;
4296                 // The only recursive bit is called here.
4297                 ShowMap(Utils->TreeRoot,user,0,matrix,totusers,totservers);
4298                 // Process each line one by one. The algorithm has a limit of
4299                 // 128 servers (which is far more than a spanning tree should have
4300                 // anyway, so we're ok). This limit can be raised simply by making
4301                 // the character matrix deeper, 128 rows taking 10k of memory.
4302                 for (int l = 1; l < line; l++)
4303                 {
4304                         // scan across the line looking for the start of the
4305                         // servername (the recursive part of the algorithm has placed
4306                         // the servers at indented positions depending on what they
4307                         // are related to)
4308                         int first_nonspace = 0;
4309                         while (matrix[l][first_nonspace] == ' ')
4310                         {
4311                                 first_nonspace++;
4312                         }
4313                         first_nonspace--;
4314                         // Draw the `- (corner) section: this may be overwritten by
4315                         // another L shape passing along the same vertical pane, becoming
4316                         // a |- (branch) section instead.
4317                         matrix[l][first_nonspace] = '-';
4318                         matrix[l][first_nonspace-1] = '`';
4319                         int l2 = l - 1;
4320                         // Draw upwards until we hit the parent server, causing possibly
4321                         // other corners (`-) to become branches (|-)
4322                         while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
4323                         {
4324                                 matrix[l2][first_nonspace-1] = '|';
4325                                 l2--;
4326                         }
4327                 }
4328                 // dump the whole lot to the user. This is the easy bit, honest.
4329                 for (int t = 0; t < line; t++)
4330                 {
4331                         user->WriteServ("006 %s :%s",user->nick,&matrix[t][0]);
4332                 }
4333                 float avg_users = totusers / totservers;
4334                 user->WriteServ("270 %s :%.0f server%s and %.0f user%s, average %.2f users per server",user->nick,totservers,(totservers > 1 ? "s" : ""),totusers,(totusers > 1 ? "s" : ""),avg_users);
4335         user->WriteServ("007 %s :End of /MAP",user->nick);
4336                 return;
4337         }
4338
4339         int HandleSquit(const char** parameters, int pcnt, userrec* user)
4340         {
4341                 TreeServer* s = Utils->FindServerMask(parameters[0]);
4342                 if (s)
4343                 {
4344                         if (s == Utils->TreeRoot)
4345                         {
4346                                  user->WriteServ("NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
4347                                 return 1;
4348                         }
4349                         TreeSocket* sock = s->GetSocket();
4350                         if (sock)
4351                         {
4352                                 ServerInstance->Log(DEBUG,"Splitting server %s",s->GetName().c_str());
4353                                 ServerInstance->SNO->WriteToSnoMask('l',"SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
4354                                 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
4355                                 ServerInstance->SE->DelFd(sock);
4356                                 sock->Close();
4357                                 delete sock;
4358                         }
4359                         else
4360                         {
4361                                 user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
4362                         }
4363                 }
4364                 else
4365                 {
4366                          user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
4367                 }
4368                 return 1;
4369         }
4370
4371         int HandleTime(const char** parameters, int pcnt, userrec* user)
4372         {
4373                 if ((IS_LOCAL(user)) && (pcnt))
4374                 {
4375                         TreeServer* found = Utils->FindServerMask(parameters[0]);
4376                         if (found)
4377                         {
4378                                 // we dont' override for local server
4379                                 if (found == Utils->TreeRoot)
4380                                         return 0;
4381                                 
4382                                 std::deque<std::string> params;
4383                                 params.push_back(found->GetName());
4384                                 params.push_back(user->nick);
4385                                 Utils->DoOneToOne(ServerInstance->Config->ServerName,"TIME",params,found->GetName());
4386                         }
4387                         else
4388                         {
4389                                 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
4390                         }
4391                 }
4392                 return 1;
4393         }
4394
4395         int HandleRemoteWhois(const char** parameters, int pcnt, userrec* user)
4396         {
4397                 if ((IS_LOCAL(user)) && (pcnt > 1))
4398                 {
4399                         userrec* remote = ServerInstance->FindNick(parameters[1]);
4400                         if ((remote) && (remote->GetFd() < 0))
4401                         {
4402                                 std::deque<std::string> params;
4403                                 params.push_back(parameters[1]);
4404                                 Utils->DoOneToOne(user->nick,"IDLE",params,remote->server);
4405                                 return 1;
4406                         }
4407                         else if (!remote)
4408                         {
4409                                 user->WriteServ("401 %s %s :No such nick/channel",user->nick, parameters[1]);
4410                                 user->WriteServ("318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
4411                                 return 1;
4412                         }
4413                 }
4414                 return 0;
4415         }
4416
4417         void DoPingChecks(time_t curtime)
4418         {
4419                 for (unsigned int j = 0; j < Utils->TreeRoot->ChildCount(); j++)
4420                 {
4421                         TreeServer* serv = Utils->TreeRoot->GetChild(j);
4422                         TreeSocket* sock = serv->GetSocket();
4423                         if (sock)
4424                         {
4425                                 if (curtime >= serv->NextPingTime())
4426                                 {
4427                                         if (serv->AnsweredLastPing())
4428                                         {
4429                                                 sock->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" PING "+serv->GetName());
4430                                                 serv->SetNextPingTime(curtime + 60);
4431                                         }
4432                                         else
4433                                         {
4434                                                 // they didnt answer, boot them
4435                                                 ServerInstance->SNO->WriteToSnoMask('l',"Server \002%s\002 pinged out",serv->GetName().c_str());
4436                                                 sock->Squit(serv,"Ping timeout");
4437                                                 ServerInstance->SE->DelFd(sock);
4438                                                 sock->Close();
4439                                                 delete sock;
4440                                                 return;
4441                                         }
4442                                 }
4443                         }
4444                 }
4445         }
4446
4447         void ConnectServer(Link* x)
4448         {
4449                 insp_inaddr binip;
4450
4451                 /* Do we already have an IP? If so, no need to resolve it. */
4452                 if (insp_aton(x->IPAddr.c_str(), &binip) > 0)
4453                 {
4454                         TreeSocket* newsocket = new TreeSocket(Utils, ServerInstance, x->IPAddr,x->Port,false,x->Timeout ? x->Timeout : 10,x->Name.c_str());
4455                         if (newsocket->GetFd() > -1)
4456                         {
4457                                 /* Handled automatically on success */
4458                         }
4459                         else
4460                         {
4461                                 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
4462                                 delete newsocket;
4463                                 Utils->DoFailOver(x);
4464                         }
4465                 }
4466                 else
4467                 {
4468                         try
4469                         {
4470                                 ServernameResolver* snr = new ServernameResolver((Module*)this, Utils, ServerInstance,x->IPAddr, *x);
4471                                 ServerInstance->AddResolver(snr);
4472                         }
4473                         catch (ModuleException& e)
4474                         {
4475                                 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
4476                                 Utils->DoFailOver(x);
4477                         }
4478                 }
4479         }
4480
4481         void AutoConnectServers(time_t curtime)
4482         {
4483                 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
4484                 {
4485                         if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
4486                         {
4487                                 ServerInstance->Log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
4488                                 x->NextConnectTime = curtime + x->AutoConnect;
4489                                 TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
4490                                 if (x->FailOver.length())
4491                                 {
4492                                         TreeServer* CheckFailOver = Utils->FindServer(x->FailOver.c_str());
4493                                         if (CheckFailOver)
4494                                         {
4495                                                 /* The failover for this server is currently a member of the network.
4496                                                  * The failover probably succeeded, where the main link did not.
4497                                                  * Don't try the main link until the failover is gone again.
4498                                                  */
4499                                                 continue;
4500                                         }
4501                                 }
4502                                 if (!CheckDupe)
4503                                 {
4504                                         // an autoconnected server is not connected. Check if its time to connect it
4505                                         ServerInstance->SNO->WriteToSnoMask('l',"AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
4506                                         this->ConnectServer(&(*x));
4507                                 }
4508                         }
4509                 }
4510         }
4511
4512         int HandleVersion(const char** parameters, int pcnt, userrec* user)
4513         {
4514                 // we've already checked if pcnt > 0, so this is safe
4515                 TreeServer* found = Utils->FindServerMask(parameters[0]);
4516                 if (found)
4517                 {
4518                         std::string Version = found->GetVersion();
4519                         user->WriteServ("351 %s :%s",user->nick,Version.c_str());
4520                         if (found == Utils->TreeRoot)
4521                         {
4522                                 std::stringstream out(ServerInstance->Config->data005);
4523                                 std::string token = "";
4524                                 std::string line5 = "";
4525                                 int token_counter = 0;
4526
4527                                 while (!out.eof())
4528                                 {
4529                                         out >> token;
4530                                         line5 = line5 + token + " ";   
4531                                         token_counter++;
4532
4533                                         if ((token_counter >= 13) || (out.eof() == true))
4534                                         {
4535                                                 user->WriteServ("005 %s %s:are supported by this server",user->nick,line5.c_str());
4536                                                 line5 = "";
4537                                                 token_counter = 0;
4538                                         }
4539                                 }
4540                         }
4541                 }
4542                 else
4543                 {
4544                         user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
4545                 }
4546                 return 1;
4547         }
4548         
4549         int HandleConnect(const char** parameters, int pcnt, userrec* user)
4550         {
4551                 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
4552                 {
4553                         if (ServerInstance->MatchText(x->Name.c_str(),parameters[0]))
4554                         {
4555                                 TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
4556                                 if (!CheckDupe)
4557                                 {
4558                                         user->WriteServ("NOTICE %s :*** CONNECT: Connecting to server: \002%s\002 (%s:%d)",user->nick,x->Name.c_str(),(x->HiddenFromStats ? "<hidden>" : x->IPAddr.c_str()),x->Port);
4559                                         ConnectServer(&(*x));
4560                                         return 1;
4561                                 }
4562                                 else
4563                                 {
4564                                         user->WriteServ("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());
4565                                         return 1;
4566                                 }
4567                         }
4568                 }
4569                 user->WriteServ("NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
4570                 return 1;
4571         }
4572
4573         void BroadcastTimeSync()
4574         {
4575                 std::deque<std::string> params;
4576                 params.push_back(ConvToStr(ServerInstance->Time(true)));
4577                 Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
4578         }
4579
4580         virtual int OnStats(char statschar, userrec* user, string_list &results)
4581         {
4582                 if (statschar == 'c')
4583                 {
4584                         for (unsigned int i = 0; i < Utils->LinkBlocks.size(); i++)
4585                         {
4586                                 results.push_back(std::string(ServerInstance->Config->ServerName)+" 213 "+user->nick+" C *@"+(Utils->LinkBlocks[i].HiddenFromStats ? "<hidden>" : Utils->LinkBlocks[i].IPAddr)+" * "+Utils->LinkBlocks[i].Name.c_str()+" "+ConvToStr(Utils->LinkBlocks[i].Port)+" "+(Utils->LinkBlocks[i].EncryptionKey != "" ? 'e' : '-')+(Utils->LinkBlocks[i].AutoConnect ? 'a' : '-')+'s');
4587                                 results.push_back(std::string(ServerInstance->Config->ServerName)+" 244 "+user->nick+" H * * "+Utils->LinkBlocks[i].Name.c_str());
4588                         }
4589                         results.push_back(std::string(ServerInstance->Config->ServerName)+" 219 "+user->nick+" "+statschar+" :End of /STATS report");
4590                         ServerInstance->SNO->WriteToSnoMask('t',"Notice: %s '%c' requested by %s (%s@%s)",(!strcmp(user->server,ServerInstance->Config->ServerName) ? "Stats" : "Remote stats"),statschar,user->nick,user->ident,user->host);
4591                         return 1;
4592                 }
4593                 return 0;
4594         }
4595
4596         virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated, const std::string &original_line)
4597         {
4598                 /* If the command doesnt appear to be valid, we dont want to mess with it. */
4599                 if (!validated)
4600                         return 0;
4601
4602                 if (command == "CONNECT")
4603                 {
4604                         return this->HandleConnect(parameters,pcnt,user);
4605                 }
4606                 else if (command == "STATS")
4607                 {
4608                         return this->HandleStats(parameters,pcnt,user);
4609                 }
4610                 else if (command == "MOTD")
4611                 {
4612                         return this->HandleMotd(parameters,pcnt,user);
4613                 }
4614                 else if (command == "ADMIN")
4615                 {
4616                         return this->HandleAdmin(parameters,pcnt,user);
4617                 }
4618                 else if (command == "SQUIT")
4619                 {
4620                         return this->HandleSquit(parameters,pcnt,user);
4621                 }
4622                 else if (command == "MAP")
4623                 {
4624                         this->HandleMap(parameters,pcnt,user);
4625                         return 1;
4626                 }
4627                 else if ((command == "TIME") && (pcnt > 0))
4628                 {
4629                         return this->HandleTime(parameters,pcnt,user);
4630                 }
4631                 else if (command == "LUSERS")
4632                 {
4633                         this->HandleLusers(parameters,pcnt,user);
4634                         return 1;
4635                 }
4636                 else if (command == "LINKS")
4637                 {
4638                         this->HandleLinks(parameters,pcnt,user);
4639                         return 1;
4640                 }
4641                 else if (command == "WHOIS")
4642                 {
4643                         if (pcnt > 1)
4644                         {
4645                                 // remote whois
4646                                 return this->HandleRemoteWhois(parameters,pcnt,user);
4647                         }
4648                 }
4649                 else if ((command == "VERSION") && (pcnt > 0))
4650                 {
4651                         this->HandleVersion(parameters,pcnt,user);
4652                         return 1;
4653                 }
4654
4655                 return 0;
4656         }
4657
4658         virtual void OnPostCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, CmdResult result, const std::string &original_line)
4659         {
4660                 if ((result == CMD_SUCCESS) && (ServerInstance->IsValidModuleCommand(command, pcnt, user)))
4661                 {
4662                         // this bit of code cleverly routes all module commands
4663                         // to all remote severs *automatically* so that modules
4664                         // can just handle commands locally, without having
4665                         // to have any special provision in place for remote
4666                         // commands and linking protocols.
4667                         std::deque<std::string> params;
4668                         params.clear();
4669                         for (int j = 0; j < pcnt; j++)
4670                         {
4671                                 if (strchr(parameters[j],' '))
4672                                 {
4673                                         params.push_back(":" + std::string(parameters[j]));
4674                                 }
4675                                 else
4676                                 {
4677                                         params.push_back(std::string(parameters[j]));
4678                                 }
4679                         }
4680                         ServerInstance->Log(DEBUG,"Globally route '%s'",command.c_str());
4681                         Utils->DoOneToMany(user->nick,command,params);
4682                 }
4683         }
4684
4685         virtual void OnGetServerDescription(const std::string &servername,std::string &description)
4686         {
4687                 TreeServer* s = Utils->FindServer(servername);
4688                 if (s)
4689                 {
4690                         description = s->GetDesc();
4691                 }
4692         }
4693
4694         virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
4695         {
4696                 if (IS_LOCAL(source))
4697                 {
4698                         std::deque<std::string> params;
4699                         params.push_back(dest->nick);
4700                         params.push_back(channel->name);
4701                         Utils->DoOneToMany(source->nick,"INVITE",params);
4702                 }
4703         }
4704
4705         virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, const std::string &topic)
4706         {
4707                 std::deque<std::string> params;
4708                 params.push_back(chan->name);
4709                 params.push_back(":"+topic);
4710                 Utils->DoOneToMany(user->nick,"TOPIC",params);
4711         }
4712
4713         virtual void OnWallops(userrec* user, const std::string &text)
4714         {
4715                 if (IS_LOCAL(user))
4716                 {
4717                         std::deque<std::string> params;
4718                         params.push_back(":"+text);
4719                         Utils->DoOneToMany(user->nick,"WALLOPS",params);
4720                 }
4721         }
4722
4723         virtual void OnUserNotice(userrec* user, void* dest, int target_type, const std::string &text, char status)
4724         {
4725                 if (target_type == TYPE_USER)
4726                 {
4727                         userrec* d = (userrec*)dest;
4728                         if ((d->GetFd() < 0) && (IS_LOCAL(user)))
4729                         {
4730                                 std::deque<std::string> params;
4731                                 params.clear();
4732                                 params.push_back(d->nick);
4733                                 params.push_back(":"+text);
4734                                 Utils->DoOneToOne(user->nick,"NOTICE",params,d->server);
4735                         }
4736                 }
4737                 else if (target_type == TYPE_CHANNEL)
4738                 {
4739                         if (IS_LOCAL(user))
4740                         {
4741                                 chanrec *c = (chanrec*)dest;
4742                                 if (c)
4743                                 {
4744                                         std::string cname = c->name;
4745                                         if (status)
4746                                                 cname = status + cname;
4747                                         std::deque<TreeServer*> list;
4748                                         Utils->GetListOfServersForChannel(c,list);
4749                                         unsigned int ucount = list.size();
4750                                         for (unsigned int i = 0; i < ucount; i++)
4751                                         {
4752                                                 TreeSocket* Sock = list[i]->GetSocket();
4753                                                 if (Sock)
4754                                                         Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+cname+" :"+text);
4755                                         }
4756                                 }
4757                         }
4758                 }
4759                 else if (target_type == TYPE_SERVER)
4760                 {
4761                         if (IS_LOCAL(user))
4762                         {
4763                                 char* target = (char*)dest;
4764                                 std::deque<std::string> par;
4765                                 par.push_back(target);
4766                                 par.push_back(":"+text);
4767                                 Utils->DoOneToMany(user->nick,"NOTICE",par);
4768                         }
4769                 }
4770         }
4771
4772         virtual void OnUserMessage(userrec* user, void* dest, int target_type, const std::string &text, char status)
4773         {
4774                 if (target_type == TYPE_USER)
4775                 {
4776                         // route private messages which are targetted at clients only to the server
4777                         // which needs to receive them
4778                         userrec* d = (userrec*)dest;
4779                         if ((d->GetFd() < 0) && (IS_LOCAL(user)))
4780                         {
4781                                 std::deque<std::string> params;
4782                                 params.clear();
4783                                 params.push_back(d->nick);
4784                                 params.push_back(":"+text);
4785                                 Utils->DoOneToOne(user->nick,"PRIVMSG",params,d->server);
4786                         }
4787                 }
4788                 else if (target_type == TYPE_CHANNEL)
4789                 {
4790                         if (IS_LOCAL(user))
4791                         {
4792                                 chanrec *c = (chanrec*)dest;
4793                                 if (c)
4794                                 {
4795                                         std::string cname = c->name;
4796                                         if (status)
4797                                                 cname = status + cname;
4798                                         std::deque<TreeServer*> list;
4799                                         Utils->GetListOfServersForChannel(c,list);
4800                                         unsigned int ucount = list.size();
4801                                         for (unsigned int i = 0; i < ucount; i++)
4802                                         {
4803                                                 TreeSocket* Sock = list[i]->GetSocket();
4804                                                 if (Sock)
4805                                                         Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+cname+" :"+text);
4806                                         }
4807                                 }
4808                         }
4809                 }
4810                 else if (target_type == TYPE_SERVER)
4811                 {
4812                         if (IS_LOCAL(user))
4813                         {
4814                                 char* target = (char*)dest;
4815                                 std::deque<std::string> par;
4816                                 par.push_back(target);
4817                                 par.push_back(":"+text);
4818                                 Utils->DoOneToMany(user->nick,"PRIVMSG",par);
4819                         }
4820                 }
4821         }
4822
4823         virtual void OnBackgroundTimer(time_t curtime)
4824         {
4825                 AutoConnectServers(curtime);
4826                 DoPingChecks(curtime);
4827         }
4828
4829         virtual void OnUserJoin(userrec* user, chanrec* channel)
4830         {
4831                 // Only do this for local users
4832                 if (IS_LOCAL(user))
4833                 {
4834                         std::deque<std::string> params;
4835                         params.clear();
4836                         params.push_back(channel->name);
4837                         // set up their permissions and the channel TS with FJOIN.
4838                         // All users are FJOINed now, because a module may specify
4839                         // new joining permissions for the user.
4840                         params.clear();
4841                         params.push_back(channel->name);
4842                         params.push_back(ConvToStr(channel->age));
4843                         params.push_back(std::string(channel->GetAllPrefixChars(user))+","+std::string(user->nick));
4844                         Utils->DoOneToMany(ServerInstance->Config->ServerName,"FJOIN",params);
4845                 }
4846         }
4847
4848         virtual void OnChangeHost(userrec* user, const std::string &newhost)
4849         {
4850                 // only occurs for local clients
4851                 if (user->registered != REG_ALL)
4852                         return;
4853                 std::deque<std::string> params;
4854                 params.push_back(newhost);
4855                 Utils->DoOneToMany(user->nick,"FHOST",params);
4856         }
4857
4858         virtual void OnChangeName(userrec* user, const std::string &gecos)
4859         {
4860                 // only occurs for local clients
4861                 if (user->registered != REG_ALL)
4862                         return;
4863                 std::deque<std::string> params;
4864                 params.push_back(gecos);
4865                 Utils->DoOneToMany(user->nick,"FNAME",params);
4866         }
4867
4868         virtual void OnUserPart(userrec* user, chanrec* channel, const std::string &partmessage)
4869         {
4870                 if (IS_LOCAL(user))
4871                 {
4872                         std::deque<std::string> params;
4873                         params.push_back(channel->name);
4874                         if (partmessage != "")
4875                                 params.push_back(":"+partmessage);
4876                         Utils->DoOneToMany(user->nick,"PART",params);
4877                 }
4878         }
4879
4880         virtual void OnUserConnect(userrec* user)
4881         {
4882                 char agestr[MAXBUF];
4883                 if (IS_LOCAL(user))
4884                 {
4885                         std::deque<std::string> params;
4886                         snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
4887                         params.push_back(agestr);
4888                         params.push_back(user->nick);
4889                         params.push_back(user->host);
4890                         params.push_back(user->dhost);
4891                         params.push_back(user->ident);
4892                         params.push_back("+"+std::string(user->FormatModes()));
4893                         params.push_back(user->GetIPString());
4894                         params.push_back(":"+std::string(user->fullname));
4895                         Utils->DoOneToMany(ServerInstance->Config->ServerName,"NICK",params);
4896
4897                         // User is Local, change needs to be reflected!
4898                         TreeServer* SourceServer = Utils->FindServer(user->server);
4899                         if (SourceServer)
4900                         {
4901                                 SourceServer->AddUserCount();
4902                         }
4903
4904                 }
4905         }
4906
4907         virtual void OnUserQuit(userrec* user, const std::string &reason)
4908         {
4909                 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
4910                 {
4911                         std::deque<std::string> params;
4912                         params.push_back(":"+reason);
4913                         Utils->DoOneToMany(user->nick,"QUIT",params);
4914                 }
4915                 // Regardless, We need to modify the user Counts..
4916                 TreeServer* SourceServer = Utils->FindServer(user->server);
4917                 if (SourceServer)
4918                 {
4919                         SourceServer->DelUserCount();
4920                 }
4921
4922         }
4923
4924         virtual void OnUserPostNick(userrec* user, const std::string &oldnick)
4925         {
4926                 if (IS_LOCAL(user))
4927                 {
4928                         std::deque<std::string> params;
4929                         params.push_back(user->nick);
4930                         Utils->DoOneToMany(oldnick,"NICK",params);
4931                 }
4932         }
4933
4934         virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, const std::string &reason)
4935         {
4936                 if ((source) && (IS_LOCAL(source)))
4937                 {
4938                         std::deque<std::string> params;
4939                         params.push_back(chan->name);
4940                         params.push_back(user->nick);
4941                         params.push_back(":"+reason);
4942                         Utils->DoOneToMany(source->nick,"KICK",params);
4943                 }
4944                 else if (!source)
4945                 {
4946                         std::deque<std::string> params;
4947                         params.push_back(chan->name);
4948                         params.push_back(user->nick);
4949                         params.push_back(":"+reason);
4950                         Utils->DoOneToMany(ServerInstance->Config->ServerName,"KICK",params);
4951                 }
4952         }
4953
4954         virtual void OnRemoteKill(userrec* source, userrec* dest, const std::string &reason)
4955         {
4956                 std::deque<std::string> params;
4957                 params.push_back(dest->nick);
4958                 params.push_back(":"+reason);
4959                 Utils->DoOneToMany(source->nick,"KILL",params);
4960         }
4961
4962         virtual void OnRehash(const std::string &parameter)
4963         {
4964                 if (parameter != "")
4965                 {
4966                         std::deque<std::string> params;
4967                         params.push_back(parameter);
4968                         Utils->DoOneToMany(ServerInstance->Config->ServerName,"REHASH",params);
4969                         // check for self
4970                         if (ServerInstance->MatchText(ServerInstance->Config->ServerName,parameter))
4971                         {
4972                                 ServerInstance->WriteOpers("*** Remote rehash initiated from server \002%s\002",ServerInstance->Config->ServerName);
4973                                 ServerInstance->RehashServer();
4974                         }
4975                 }
4976                 Utils->ReadConfiguration(false);
4977         }
4978
4979         // note: the protocol does not allow direct umode +o except
4980         // via NICK with 8 params. sending OPERTYPE infers +o modechange
4981         // locally.
4982         virtual void OnOper(userrec* user, const std::string &opertype)
4983         {
4984                 if (IS_LOCAL(user))
4985                 {
4986                         std::deque<std::string> params;
4987                         params.push_back(opertype);
4988                         Utils->DoOneToMany(user->nick,"OPERTYPE",params);
4989                 }
4990         }
4991
4992         void OnLine(userrec* source, const std::string &host, bool adding, char linetype, long duration, const std::string &reason)
4993         {
4994                 if (!source)
4995                 {
4996                         /* Server-set lines */
4997                         char data[MAXBUF];
4998                         snprintf(data,MAXBUF,"%c %s %s %lu %lu :%s", linetype, host.c_str(), ServerInstance->Config->ServerName, (unsigned long)ServerInstance->Time(false),
4999                                         (unsigned long)duration, reason.c_str());
5000                         std::deque<std::string> params;
5001                         params.push_back(data);
5002                         Utils->DoOneToMany(ServerInstance->Config->ServerName, "ADDLINE", params);
5003                 }
5004                 else
5005                 {
5006                         if (IS_LOCAL(source))
5007                         {
5008                                 char type[8];
5009                                 snprintf(type,8,"%cLINE",linetype);
5010                                 std::string stype = type;
5011                                 if (adding)
5012                                 {
5013                                         char sduration[MAXBUF];
5014                                         snprintf(sduration,MAXBUF,"%ld",duration);
5015                                         std::deque<std::string> params;
5016                                         params.push_back(host);
5017                                         params.push_back(sduration);
5018                                         params.push_back(":"+reason);
5019                                         Utils->DoOneToMany(source->nick,stype,params);
5020                                 }
5021                                 else
5022                                 {
5023                                         std::deque<std::string> params;
5024                                         params.push_back(host);
5025                                         Utils->DoOneToMany(source->nick,stype,params);
5026                                 }
5027                         }
5028                 }
5029         }
5030
5031         virtual void OnAddGLine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
5032         {
5033                 OnLine(source,hostmask,true,'G',duration,reason);
5034         }
5035         
5036         virtual void OnAddZLine(long duration, userrec* source, const std::string &reason, const std::string &ipmask)
5037         {
5038                 OnLine(source,ipmask,true,'Z',duration,reason);
5039         }
5040
5041         virtual void OnAddQLine(long duration, userrec* source, const std::string &reason, const std::string &nickmask)
5042         {
5043                 OnLine(source,nickmask,true,'Q',duration,reason);
5044         }
5045
5046         virtual void OnAddELine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
5047         {
5048                 OnLine(source,hostmask,true,'E',duration,reason);
5049         }
5050
5051         virtual void OnDelGLine(userrec* source, const std::string &hostmask)
5052         {
5053                 OnLine(source,hostmask,false,'G',0,"");
5054         }
5055
5056         virtual void OnDelZLine(userrec* source, const std::string &ipmask)
5057         {
5058                 OnLine(source,ipmask,false,'Z',0,"");
5059         }
5060
5061         virtual void OnDelQLine(userrec* source, const std::string &nickmask)
5062         {
5063                 OnLine(source,nickmask,false,'Q',0,"");
5064         }
5065
5066         virtual void OnDelELine(userrec* source, const std::string &hostmask)
5067         {
5068                 OnLine(source,hostmask,false,'E',0,"");
5069         }
5070
5071         virtual void OnMode(userrec* user, void* dest, int target_type, const std::string &text)
5072         {
5073                 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
5074                 {
5075                         if (target_type == TYPE_USER)
5076                         {
5077                                 userrec* u = (userrec*)dest;
5078                                 std::deque<std::string> params;
5079                                 params.push_back(u->nick);
5080                                 params.push_back(text);
5081                                 Utils->DoOneToMany(user->nick,"MODE",params);
5082                         }
5083                         else
5084                         {
5085                                 chanrec* c = (chanrec*)dest;
5086                                 std::deque<std::string> params;
5087                                 params.push_back(c->name);
5088                                 params.push_back(text);
5089                                 Utils->DoOneToMany(user->nick,"MODE",params);
5090                         }
5091                 }
5092         }
5093
5094         virtual void OnSetAway(userrec* user)
5095         {
5096                 if (IS_LOCAL(user))
5097                 {
5098                         std::deque<std::string> params;
5099                         params.push_back(":"+std::string(user->awaymsg));
5100                         Utils->DoOneToMany(user->nick,"AWAY",params);
5101                 }
5102         }
5103
5104         virtual void OnCancelAway(userrec* user)
5105         {
5106                 if (IS_LOCAL(user))
5107                 {
5108                         std::deque<std::string> params;
5109                         params.clear();
5110                         Utils->DoOneToMany(user->nick,"AWAY",params);
5111                 }
5112         }
5113
5114         virtual void ProtoSendMode(void* opaque, int target_type, void* target, const std::string &modeline)
5115         {
5116                 TreeSocket* s = (TreeSocket*)opaque;
5117                 if (target)
5118                 {
5119                         if (target_type == TYPE_USER)
5120                         {
5121                                 userrec* u = (userrec*)target;
5122                                 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+u->nick+" "+ConvToStr(u->age)+" "+modeline);
5123                         }
5124                         else
5125                         {
5126                                 chanrec* c = (chanrec*)target;
5127                                 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age)+" "+modeline);
5128                         }
5129                 }
5130         }
5131
5132         virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, const std::string &extname, const std::string &extdata)
5133         {
5134                 TreeSocket* s = (TreeSocket*)opaque;
5135                 if (target)
5136                 {
5137                         if (target_type == TYPE_USER)
5138                         {
5139                                 userrec* u = (userrec*)target;
5140                                 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+u->nick+" "+extname+" :"+extdata);
5141                         }
5142                         else if (target_type == TYPE_OTHER)
5143                         {
5144                                 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA * "+extname+" :"+extdata);
5145                         }
5146                         else if (target_type == TYPE_CHANNEL)
5147                         {
5148                                 chanrec* c = (chanrec*)target;
5149                                 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+c->name+" "+extname+" :"+extdata);
5150                         }
5151                 }
5152         }
5153
5154         virtual void OnEvent(Event* event)
5155         {
5156                 std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
5157
5158                 if (event->GetEventID() == "send_metadata")
5159                 {
5160                         if (params->size() < 3)
5161                                 return;
5162                         (*params)[2] = ":" + (*params)[2];
5163                         Utils->DoOneToMany(ServerInstance->Config->ServerName,"METADATA",*params);
5164                 }
5165                 else if (event->GetEventID() == "send_topic")
5166                 {
5167                         if (params->size() < 2)
5168                                 return;
5169                         (*params)[1] = ":" + (*params)[1];
5170                         params->insert(params->begin() + 1,ServerInstance->Config->ServerName);
5171                         params->insert(params->begin() + 1,ConvToStr(ServerInstance->Time(true)));
5172                         Utils->DoOneToMany(ServerInstance->Config->ServerName,"FTOPIC",*params);
5173                 }
5174                 else if (event->GetEventID() == "send_mode")
5175                 {
5176                         if (params->size() < 2)
5177                                 return;
5178                         // Insert the TS value of the object, either userrec or chanrec
5179                         time_t ourTS = 0;
5180                         userrec* a = ServerInstance->FindNick((*params)[0]);
5181                         if (a)
5182                         {
5183                                 ourTS = a->age;
5184                         }
5185                         else
5186                         {
5187                                 chanrec* a = ServerInstance->FindChan((*params)[0]);
5188                                 if (a)
5189                                 {
5190                                         ourTS = a->age;
5191                                 }
5192                         }
5193                         params->insert(params->begin() + 1,ConvToStr(ourTS));
5194                         Utils->DoOneToMany(ServerInstance->Config->ServerName,"FMODE",*params);
5195                 }
5196                 else if (event->GetEventID() == "send_mode_explicit")
5197                 {
5198                         if (params->size() < 2)
5199                                 return;
5200                         Utils->DoOneToMany(ServerInstance->Config->ServerName,"MODE",*params);
5201                 }
5202                 else if (event->GetEventID() == "send_opers")
5203                 {
5204                         if (params->size() < 1)
5205                                 return;
5206                         (*params)[0] = ":" + (*params)[0];
5207                         Utils->DoOneToMany(ServerInstance->Config->ServerName,"OPERNOTICE",*params);
5208                 }
5209                 else if (event->GetEventID() == "send_modeset")
5210                 {
5211                         if (params->size() < 2)
5212                                 return;
5213                         (*params)[1] = ":" + (*params)[1];
5214                         Utils->DoOneToMany(ServerInstance->Config->ServerName,"MODENOTICE",*params);
5215                 }
5216                 else if (event->GetEventID() == "send_snoset")
5217                 {
5218                         if (params->size() < 2)
5219                                 return;
5220                         (*params)[1] = ":" + (*params)[1];
5221                         Utils->DoOneToMany(ServerInstance->Config->ServerName,"SNONOTICE",*params);
5222                 }
5223                 else if (event->GetEventID() == "send_push")
5224                 {
5225                         if (params->size() < 2)
5226                                 return;
5227                         
5228                         userrec *a = ServerInstance->FindNick((*params)[0]);
5229                         
5230                         if (!a)
5231                                 return;
5232                         
5233                         (*params)[1] = ":" + (*params)[1];
5234                         Utils->DoOneToOne(ServerInstance->Config->ServerName, "PUSH", *params, a->server);
5235                 }
5236         }
5237
5238         virtual ~ModuleSpanningTree()
5239         {
5240                 ServerInstance->Log(DEBUG,"Performing unload of spanningtree!");
5241                 /* This will also free the listeners */
5242                 delete Utils;
5243                 if (SyncTimer)
5244                         ServerInstance->Timers->DelTimer(SyncTimer);
5245         }
5246
5247         virtual Version GetVersion()
5248         {
5249                 return Version(1,1,0,2,VF_VENDOR,API_VERSION);
5250         }
5251
5252         void Implements(char* List)
5253         {
5254                 List[I_OnPreCommand] = List[I_OnGetServerDescription] = List[I_OnUserInvite] = List[I_OnPostLocalTopicChange] = 1;
5255                 List[I_OnWallops] = List[I_OnUserNotice] = List[I_OnUserMessage] = List[I_OnBackgroundTimer] = 1;
5256                 List[I_OnUserJoin] = List[I_OnChangeHost] = List[I_OnChangeName] = List[I_OnUserPart] = List[I_OnUserConnect] = 1;
5257                 List[I_OnUserQuit] = List[I_OnUserPostNick] = List[I_OnUserKick] = List[I_OnRemoteKill] = List[I_OnRehash] = 1;
5258                 List[I_OnOper] = List[I_OnAddGLine] = List[I_OnAddZLine] = List[I_OnAddQLine] = List[I_OnAddELine] = 1;
5259                 List[I_OnDelGLine] = List[I_OnDelZLine] = List[I_OnDelQLine] = List[I_OnDelELine] = List[I_ProtoSendMode] = List[I_OnMode] = 1;
5260                 List[I_OnStats] = List[I_ProtoSendMetaData] = List[I_OnEvent] = List[I_OnSetAway] = List[I_OnCancelAway] = List[I_OnPostCommand] = 1;
5261         }
5262
5263         /* It is IMPORTANT that m_spanningtree is the last module in the chain
5264          * so that any activity it sees is FINAL, e.g. we arent going to send out
5265          * a NICK message before m_cloaking has finished putting the +x on the user,
5266          * etc etc.
5267          * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
5268          * the module call queue.
5269          */
5270         Priority Prioritize()
5271         {
5272                 return PRIORITY_LAST;
5273         }
5274 };
5275
5276 TimeSyncTimer::TimeSyncTimer(InspIRCd *Inst, ModuleSpanningTree *Mod) : InspTimer(43200, Inst->Time()), Instance(Inst), Module(Mod)
5277 {
5278 }
5279
5280 void TimeSyncTimer::Tick(time_t TIME)
5281 {
5282         Module->BroadcastTimeSync();
5283         Module->SyncTimer = new TimeSyncTimer(Instance, Module);
5284         Instance->Timers->AddTimer(Module->SyncTimer);
5285 }
5286
5287 void SpanningTreeUtilities::DoFailOver(Link* x)
5288 {
5289         if (x->FailOver.length())
5290         {
5291                 if (x->FailOver == x->Name)
5292                 {
5293                         ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Some muppet configured the failover for server \002%s\002 to point at itself. Not following it!", x->Name.c_str());
5294                         return;
5295                 }
5296                 Link* TryThisOne = this->FindLink(x->FailOver.c_str());
5297                 if (TryThisOne)
5298                 {
5299                         ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Trying failover link for \002%s\002: \002%s\002...", x->Name.c_str(), TryThisOne->Name.c_str());
5300                         Creator->ConnectServer(TryThisOne);
5301                 }
5302                 else
5303                 {
5304                         ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Invalid failover server specified for server \002%s\002, will not follow!", x->Name.c_str());
5305                 }
5306         }
5307 }
5308
5309 Link* SpanningTreeUtilities::FindLink(const std::string& name)
5310 {
5311         for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
5312         {
5313                 if (ServerInstance->MatchText(x->Name.c_str(), name.c_str()))
5314                 {
5315                         return &(*x);
5316                 }
5317         }
5318         return NULL;
5319 }
5320
5321 class ModuleSpanningTreeFactory : public ModuleFactory
5322 {
5323  public:
5324         ModuleSpanningTreeFactory()
5325         {
5326         }
5327         
5328         ~ModuleSpanningTreeFactory()
5329         {
5330         }
5331         
5332         virtual Module * CreateModule(InspIRCd* Me)
5333         {
5334                 return new ModuleSpanningTree(Me);
5335         }
5336         
5337 };
5338
5339
5340 extern "C" void * init_module( void )
5341 {
5342         return new ModuleSpanningTreeFactory;
5343 }