]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree.cpp
80b5cc5042c795c0f5020c73a9c3053df72b86dc
[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 = 1101;
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 == "ENDBURST")
3406                                 {
3407                                         this->bursting = false;
3408                                         Instance->XLines->apply_lines(APPLY_ZLINES|APPLY_GLINES|APPLY_QLINES);
3409                                         std::string sourceserv = this->myhost;
3410                                         if (this->InboundServerName != "")
3411                                         {
3412                                                 sourceserv = this->InboundServerName;
3413                                         }
3414                                         this->Instance->SNO->WriteToSnoMask('l',"Received end of netburst from \2%s\2",sourceserv.c_str());
3415
3416                                         Event rmode((char*)sourceserv.c_str(), (Module*)Utils->Creator, "new_server");
3417                                         rmode.Send(Instance);
3418
3419                                         return true;
3420                                 }
3421                                 else
3422                                 {
3423                                         // not a special inter-server command.
3424                                         // Emulate the actual user doing the command,
3425                                         // this saves us having a huge ugly parser.
3426                                         userrec* who = this->Instance->FindNick(prefix);
3427                                         std::string sourceserv = this->myhost;
3428                                         if (this->InboundServerName != "")
3429                                         {
3430                                                 sourceserv = this->InboundServerName;
3431                                         }
3432                                         if ((!who) && (command == "MODE"))
3433                                         {
3434                                                 if (Utils->IsServer(prefix))
3435                                                 {
3436                                                         const char* modelist[127];
3437                                                         for (size_t i = 0; i < params.size(); i++)
3438                                                                 modelist[i] = params[i].c_str();
3439
3440                                                         userrec* fake = new userrec(Instance);
3441                                                         fake->SetFd(FD_MAGIC_NUMBER);
3442
3443                                                         this->Instance->SendMode(modelist, params.size(), fake);
3444         
3445                                                         delete fake;
3446                                                 }
3447                                         }
3448                                         if (who)
3449                                         {
3450                                                 if ((command == "NICK") && (params.size() > 0))
3451                                                 {
3452                                                         /* On nick messages, check that the nick doesnt
3453                                                          * already exist here. If it does, kill their copy,
3454                                                          * and our copy.
3455                                                          */
3456                                                         userrec* x = this->Instance->FindNick(params[0]);
3457                                                         if ((x) && (x != who))
3458                                                         {
3459                                                                 std::deque<std::string> p;
3460                                                                 p.push_back(params[0]);
3461                                                                 p.push_back("Nickname collision ("+prefix+" -> "+params[0]+")");
3462                                                                 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
3463                                                                 p.clear();
3464                                                                 p.push_back(prefix);
3465                                                                 p.push_back("Nickname collision");
3466                                                                 Utils->DoOneToMany(this->Instance->Config->ServerName,"KILL",p);
3467                                                                 userrec::QuitUser(this->Instance,x,"Nickname collision ("+prefix+" -> "+params[0]+")");
3468                                                                 userrec* y = this->Instance->FindNick(prefix);
3469                                                                 if (y)
3470                                                                 {
3471                                                                         userrec::QuitUser(this->Instance,y,"Nickname collision");
3472                                                                 }
3473                                                                 return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3474                                                         }
3475                                                 }
3476                                                 // its a user
3477                                                 target = who->server;
3478                                                 const char* strparams[127];
3479                                                 for (unsigned int q = 0; q < params.size(); q++)
3480                                                 {
3481                                                         strparams[q] = params[q].c_str();
3482                                                 }
3483                                                 switch (this->Instance->CallCommandHandler(command.c_str(), strparams, params.size(), who))
3484                                                 {
3485                                                         case CMD_INVALID:
3486                                                                 this->WriteLine("ERROR :Unrecognised command '"+std::string(command.c_str())+"' -- possibly loaded mismatched modules");
3487                                                                 return false;
3488                                                         break;
3489                                                         case CMD_FAILURE:
3490                                                                 return true;
3491                                                         break;
3492                                                         default:
3493                                                                 /* CMD_SUCCESS and CMD_USER_DELETED fall through here */
3494                                                         break;
3495                                                 }
3496                                         }
3497                                         else
3498                                         {
3499                                                 // its not a user. Its either a server, or somethings screwed up.
3500                                                 if (Utils->IsServer(prefix))
3501                                                 {
3502                                                         target = this->Instance->Config->ServerName;
3503                                                 }
3504                                                 else
3505                                                 {
3506                                                         Instance->Log(DEBUG,"Command with unknown origin '%s'",prefix.c_str());
3507                                                         return true;
3508                                                 }
3509                                         }
3510                                         return Utils->DoOneToAllButSenderRaw(line,sourceserv,prefix,command,params);
3511
3512                                 }
3513                                 return true;
3514                         break;
3515                 }
3516                 return true;
3517         }
3518
3519         virtual std::string GetName()
3520         {
3521                 std::string sourceserv = this->myhost;
3522                 if (this->InboundServerName != "")
3523                 {
3524                         sourceserv = this->InboundServerName;
3525                 }
3526                 return sourceserv;
3527         }
3528
3529         virtual void OnTimeout()
3530         {
3531                 if (this->LinkState == CONNECTING)
3532                 {
3533                         this->Instance->SNO->WriteToSnoMask('l',"CONNECT: Connection to \002"+myhost+"\002 timed out.");
3534                         Link* MyLink = Utils->FindLink(myhost);
3535                         if (MyLink)
3536                                 Utils->DoFailOver(MyLink);
3537                 }
3538         }
3539
3540         virtual void OnClose()
3541         {
3542                 // Connection closed.
3543                 // If the connection is fully up (state CONNECTED)
3544                 // then propogate a netsplit to all peers.
3545                 std::string quitserver = this->myhost;
3546                 if (this->InboundServerName != "")
3547                 {
3548                         quitserver = this->InboundServerName;
3549                 }
3550                 TreeServer* s = Utils->FindServer(quitserver);
3551                 if (s)
3552                 {
3553                         Squit(s,"Remote host closed the connection");
3554                 }
3555
3556                 if (quitserver != "")
3557                         this->Instance->SNO->WriteToSnoMask('l',"Connection to '\2%s\2' failed.",quitserver.c_str());
3558         }
3559
3560         virtual int OnIncomingConnection(int newsock, char* ip)
3561         {
3562                 /* To prevent anyone from attempting to flood opers/DDoS by connecting to the server port,
3563                  * or discovering if this port is the server port, we don't allow connections from any
3564                  * IPs for which we don't have a link block.
3565                  */
3566                 bool found = false;
3567
3568                 found = (std::find(Utils->ValidIPs.begin(), Utils->ValidIPs.end(), ip) != Utils->ValidIPs.end());
3569                 if (!found)
3570                 {
3571                         for (vector<std::string>::iterator i = Utils->ValidIPs.begin(); i != Utils->ValidIPs.end(); i++)
3572                                 if (irc::sockets::MatchCIDR(ip, (*i).c_str()))
3573                                         found = true;
3574
3575                         if (!found)
3576                         {
3577                                 this->Instance->SNO->WriteToSnoMask('l',"Server connection from %s denied (no link blocks with that IP address)", ip);
3578                                 close(newsock);
3579                                 return false;
3580                         }
3581                 }
3582                 TreeSocket* s = new TreeSocket(this->Utils, this->Instance, newsock, ip);
3583                 s = s; /* Whinge whinge whinge, thats all GCC ever does. */
3584                 return true;
3585         }
3586 };
3587
3588 /** This class is used to resolve server hostnames during /connect and autoconnect.
3589  * As of 1.1, the resolver system is seperated out from InspSocket, so we must do this
3590  * resolver step first ourselves if we need it. This is totally nonblocking, and will
3591  * callback to OnLookupComplete or OnError when completed. Once it has completed we
3592  * will have an IP address which we can then use to continue our connection.
3593  */
3594 class ServernameResolver : public Resolver
3595 {       
3596  private:
3597         /** A copy of the Link tag info for what we're connecting to.
3598          * We take a copy, rather than using a pointer, just in case the
3599          * admin takes the tag away and rehashes while the domain is resolving.
3600          */
3601         Link MyLink;
3602         SpanningTreeUtilities* Utils;
3603  public: 
3604         ServernameResolver(Module* me, SpanningTreeUtilities* Util, InspIRCd* Instance, const std::string &hostname, Link x) : Resolver(Instance, hostname, DNS_QUERY_FORWARD, me), MyLink(x), Utils(Util)
3605         {
3606                 /* Nothing in here, folks */
3607         }
3608
3609         void OnLookupComplete(const std::string &result)
3610         {
3611                 /* Initiate the connection, now that we have an IP to use.
3612                  * Passing a hostname directly to InspSocket causes it to
3613                  * just bail and set its FD to -1.
3614                  */
3615                 TreeServer* CheckDupe = Utils->FindServer(MyLink.Name.c_str());
3616                 if (!CheckDupe) /* Check that nobody tried to connect it successfully while we were resolving */
3617                 {
3618                         TreeSocket* newsocket = new TreeSocket(this->Utils, ServerInstance, result,MyLink.Port,false,MyLink.Timeout ? MyLink.Timeout : 10,MyLink.Name.c_str());
3619                         if (newsocket->GetFd() > -1)
3620                         {
3621                                 /* We're all OK */
3622                         }
3623                         else
3624                         {
3625                                 /* Something barfed, show the opers */
3626                                 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",MyLink.Name.c_str(),strerror(errno));
3627                                 delete newsocket;
3628                                 Utils->DoFailOver(&MyLink);
3629                         }
3630                 }
3631         }
3632
3633         void OnError(ResolverError e, const std::string &errormessage)
3634         {
3635                 /* Ooops! */
3636                 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: Unable to resolve hostname - %s",MyLink.Name.c_str(),errormessage.c_str());
3637                 Utils->DoFailOver(&MyLink);
3638         }
3639 };
3640
3641 /** Handle resolving of server IPs for the cache
3642  */
3643 class SecurityIPResolver : public Resolver
3644 {
3645  private:
3646         Link MyLink;
3647         SpanningTreeUtilities* Utils;
3648  public:
3649         SecurityIPResolver(Module* me, SpanningTreeUtilities* U, InspIRCd* Instance, const std::string &hostname, Link x) : Resolver(Instance, hostname, DNS_QUERY_FORWARD, me), MyLink(x), Utils(U)
3650         {
3651         }
3652
3653         void OnLookupComplete(const std::string &result)
3654         {
3655                 ServerInstance->Log(DEBUG,"Security IP cache: Adding IP address '%s' for Link '%s'",result.c_str(),MyLink.Name.c_str());
3656                 Utils->ValidIPs.push_back(result);
3657         }
3658
3659         void OnError(ResolverError e, const std::string &errormessage)
3660         {
3661                 ServerInstance->Log(DEBUG,"Could not resolve IP associated with Link '%s': %s",MyLink.Name.c_str(),errormessage.c_str());
3662         }
3663 };
3664
3665 SpanningTreeUtilities::SpanningTreeUtilities(InspIRCd* Instance, ModuleSpanningTree* C) : ServerInstance(Instance), Creator(C)
3666 {
3667         Bindings.clear();
3668         this->ReadConfiguration(true);
3669         this->TreeRoot = new TreeServer(this, ServerInstance, ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc);
3670 }
3671
3672 SpanningTreeUtilities::~SpanningTreeUtilities()
3673 {
3674         for (unsigned int i = 0; i < Bindings.size(); i++)
3675         {
3676                 ServerInstance->Log(DEBUG,"Freeing binding %d of %d",i, Bindings.size());
3677                 ServerInstance->SE->DelFd(Bindings[i]);
3678                 Bindings[i]->Close();
3679                 DELETE(Bindings[i]);
3680         }
3681         ServerInstance->Log(DEBUG,"Freeing connected servers...");
3682         while (TreeRoot->ChildCount())
3683         {
3684                 TreeServer* child_server = TreeRoot->GetChild(0);
3685                 ServerInstance->Log(DEBUG,"Freeing connected server %s", child_server->GetName().c_str());
3686                 if (child_server)
3687                 {
3688                         TreeSocket* sock = child_server->GetSocket();
3689                         ServerInstance->SE->DelFd(sock);
3690                         sock->Close();
3691                         DELETE(sock);
3692                 }
3693         }
3694         delete TreeRoot;
3695 }
3696
3697 void SpanningTreeUtilities::AddThisServer(TreeServer* server, std::deque<TreeServer*> &list)
3698 {
3699         for (unsigned int c = 0; c < list.size(); c++)
3700         {
3701                 if (list[c] == server)
3702                 {
3703                         return;
3704                 }
3705         }
3706         list.push_back(server);
3707 }
3708
3709 /** returns a list of DIRECT servernames for a specific channel */
3710 void SpanningTreeUtilities::GetListOfServersForChannel(chanrec* c, std::deque<TreeServer*> &list)
3711 {
3712         CUList *ulist = c->GetUsers();
3713         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
3714         {
3715                 if (i->second->GetFd() < 0)
3716                 {
3717                         TreeServer* best = this->BestRouteTo(i->second->server);
3718                         if (best)
3719                                 AddThisServer(best,list);
3720                 }
3721         }
3722         return;
3723 }
3724
3725 bool SpanningTreeUtilities::DoOneToAllButSenderRaw(const std::string &data, const std::string &omit, const std::string &prefix, const irc::string &command, std::deque<std::string> &params)
3726 {
3727         TreeServer* omitroute = this->BestRouteTo(omit);
3728         if ((command == "NOTICE") || (command == "PRIVMSG"))
3729         {
3730                 if (params.size() >= 2)
3731                 {
3732                         /* Prefixes */
3733                         if ((*(params[0].c_str()) == '@') || (*(params[0].c_str()) == '%') || (*(params[0].c_str()) == '+'))
3734                         {
3735                                 params[0] = params[0].substr(1, params[0].length()-1);
3736                         }
3737                         if ((*(params[0].c_str()) != '#') && (*(params[0].c_str()) != '$'))
3738                         {
3739                                 // special routing for private messages/notices
3740                                 userrec* d = ServerInstance->FindNick(params[0]);
3741                                 if (d)
3742                                 {
3743                                         std::deque<std::string> par;
3744                                         par.push_back(params[0]);
3745                                         par.push_back(":"+params[1]);
3746                                         this->DoOneToOne(prefix,command.c_str(),par,d->server);
3747                                         return true;
3748                                 }
3749                         }
3750                         else if (*(params[0].c_str()) == '$')
3751                         {
3752                                 std::deque<std::string> par;
3753                                 par.push_back(params[0]);
3754                                 par.push_back(":"+params[1]);
3755                                 this->DoOneToAllButSender(prefix,command.c_str(),par,omitroute->GetName());
3756                                 return true;
3757                         }
3758                         else
3759                         {
3760                                 chanrec* c = ServerInstance->FindChan(params[0]);
3761                                 if (c)
3762                                 {
3763                                         std::deque<TreeServer*> list;
3764                                         GetListOfServersForChannel(c,list);
3765                                         unsigned int lsize = list.size();
3766                                         for (unsigned int i = 0; i < lsize; i++)
3767                                         {
3768                                                 TreeSocket* Sock = list[i]->GetSocket();
3769                                                 if ((Sock) && (list[i]->GetName() != omit) && (omitroute != list[i]))
3770                                                 {
3771                                                         Sock->WriteLine(data);
3772                                                 }
3773                                         }
3774                                         return true;
3775                                 }
3776                         }
3777                 }
3778         }
3779         unsigned int items =this->TreeRoot->ChildCount();
3780         for (unsigned int x = 0; x < items; x++)
3781         {
3782                 TreeServer* Route = this->TreeRoot->GetChild(x);
3783                 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3784                 {
3785                         TreeSocket* Sock = Route->GetSocket();
3786                         if (Sock)
3787                                 Sock->WriteLine(data);
3788                 }
3789         }
3790         return true;
3791 }
3792
3793 bool SpanningTreeUtilities::DoOneToAllButSender(const std::string &prefix, const std::string &command, std::deque<std::string> &params, std::string omit)
3794 {
3795         TreeServer* omitroute = this->BestRouteTo(omit);
3796         std::string FullLine = ":" + prefix + " " + command;
3797         unsigned int words = params.size();
3798         for (unsigned int x = 0; x < words; x++)
3799         {
3800                 FullLine = FullLine + " " + params[x];
3801         }
3802         unsigned int items = this->TreeRoot->ChildCount();
3803         for (unsigned int x = 0; x < items; x++)
3804         {
3805                 TreeServer* Route = this->TreeRoot->GetChild(x);
3806                 // Send the line IF:
3807                 // The route has a socket (its a direct connection)
3808                 // The route isnt the one to be omitted
3809                 // The route isnt the path to the one to be omitted
3810                 if ((Route) && (Route->GetSocket()) && (Route->GetName() != omit) && (omitroute != Route))
3811                 {
3812                         TreeSocket* Sock = Route->GetSocket();
3813                         if (Sock)
3814                                 Sock->WriteLine(FullLine);
3815                 }
3816         }
3817         return true;
3818 }
3819
3820 bool SpanningTreeUtilities::DoOneToMany(const std::string &prefix, const std::string &command, std::deque<std::string> &params)
3821 {
3822         std::string FullLine = ":" + prefix + " " + command;
3823         unsigned int words = params.size();
3824         for (unsigned int x = 0; x < words; x++)
3825         {
3826                 FullLine = FullLine + " " + params[x];
3827         }
3828         unsigned int items = this->TreeRoot->ChildCount();
3829         for (unsigned int x = 0; x < items; x++)
3830         {
3831                 TreeServer* Route = this->TreeRoot->GetChild(x);
3832                 if (Route && Route->GetSocket())
3833                 {
3834                         TreeSocket* Sock = Route->GetSocket();
3835                         if (Sock)
3836                                 Sock->WriteLine(FullLine);
3837                 }
3838         }
3839         return true;
3840 }
3841
3842 bool SpanningTreeUtilities::DoOneToMany(const char* prefix, const char* command, std::deque<std::string> &params)
3843 {
3844         std::string spfx = prefix;
3845         std::string scmd = command;
3846         return this->DoOneToMany(spfx, scmd, params);
3847 }
3848
3849 bool SpanningTreeUtilities::DoOneToAllButSender(const char* prefix, const char* command, std::deque<std::string> &params, std::string omit)
3850 {
3851         std::string spfx = prefix;
3852         std::string scmd = command;
3853         return this->DoOneToAllButSender(spfx, scmd, params, omit);
3854 }
3855         
3856 bool SpanningTreeUtilities::DoOneToOne(const std::string &prefix, const std::string &command, std::deque<std::string> &params, std::string target)
3857 {
3858         TreeServer* Route = this->BestRouteTo(target);
3859         if (Route)
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                 if (Route && Route->GetSocket())
3868                 {
3869                         TreeSocket* Sock = Route->GetSocket();
3870                         if (Sock)
3871                                 Sock->WriteLine(FullLine);
3872                 }
3873                 return true;
3874         }
3875         else
3876         {
3877                 return false;
3878         }
3879 }
3880
3881 void SpanningTreeUtilities::ReadConfiguration(bool rebind)
3882 {
3883         ConfigReader* Conf = new ConfigReader(ServerInstance);
3884         if (rebind)
3885         {
3886                 for (int j =0; j < Conf->Enumerate("bind"); j++)
3887                 {
3888                         std::string Type = Conf->ReadValue("bind","type",j);
3889                         std::string IP = Conf->ReadValue("bind","address",j);
3890                         std::string Port = Conf->ReadValue("bind","port",j);
3891                         if (Type == "servers")
3892                         {
3893                                 irc::portparser portrange(Port, false);
3894                                 int portno = -1;
3895                                 while ((portno = portrange.GetToken()))
3896                                 {
3897                                         ServerInstance->Log(DEBUG,"m_spanningtree: Binding server port %s:%d", IP.c_str(), portno);
3898                                         if (IP == "*")
3899                                                 IP = "";
3900
3901                                         TreeSocket* listener = new TreeSocket(this, ServerInstance, IP.c_str(), portno, true, 10);
3902                                         if (listener->GetState() == I_LISTENING)
3903                                         {
3904                                                 ServerInstance->Log(DEFAULT,"m_spanningtree: Binding server port %s:%d successful!", IP.c_str(), portno);
3905                                                 Bindings.push_back(listener);
3906                                         }
3907                                         else
3908                                         {
3909                                                 ServerInstance->Log(DEFAULT,"m_spanningtree: Warning: Failed to bind server port %s:%d",IP.c_str(), portno);
3910                                                 listener->Close();
3911                                                 DELETE(listener);
3912                                         }
3913                                         ServerInstance->Log(DEBUG,"Done with this binding");
3914                                 }
3915                         }
3916                 }
3917         }
3918         FlatLinks = Conf->ReadFlag("options","flatlinks",0);
3919         HideULines = Conf->ReadFlag("options","hideulines",0);
3920         AnnounceTSChange = Conf->ReadFlag("options","announcets",0);
3921         EnableTimeSync = !(Conf->ReadFlag("options","notimesync",0));
3922         LinkBlocks.clear();
3923         ValidIPs.clear();
3924         for (int j =0; j < Conf->Enumerate("link"); j++)
3925         {
3926                 Link L;
3927                 std::string Allow = Conf->ReadValue("link","allowmask",j);
3928                 L.Name = (Conf->ReadValue("link","name",j)).c_str();
3929                 L.IPAddr = Conf->ReadValue("link","ipaddr",j);
3930                 L.FailOver = Conf->ReadValue("link","failover",j).c_str();
3931                 L.Port = Conf->ReadInteger("link","port",j,true);
3932                 L.SendPass = Conf->ReadValue("link","sendpass",j);
3933                 L.RecvPass = Conf->ReadValue("link","recvpass",j);
3934                 L.AutoConnect = Conf->ReadInteger("link","autoconnect",j,true);
3935                 L.EncryptionKey =  Conf->ReadValue("link","encryptionkey",j);
3936                 L.HiddenFromStats = Conf->ReadFlag("link","hidden",j);
3937                 L.Timeout = Conf->ReadInteger("link","timeout",j,true);
3938                 L.NextConnectTime = time(NULL) + L.AutoConnect;
3939                 /* Bugfix by brain, do not allow people to enter bad configurations */
3940                 if (L.Name != ServerInstance->Config->ServerName)
3941                 {
3942                         if ((L.IPAddr != "") && (L.RecvPass != "") && (L.SendPass != "") && (L.Name != "") && (L.Port))
3943                         {
3944                                 ValidIPs.push_back(L.IPAddr);
3945
3946                                 if (Allow.length())
3947                                         ValidIPs.push_back(Allow);
3948
3949                                 /* Needs resolving */
3950                                 insp_inaddr binip;
3951                                 if (insp_aton(L.IPAddr.c_str(), &binip) < 1)
3952                                 {
3953                                         try
3954                                         {
3955                                                 SecurityIPResolver* sr = new SecurityIPResolver((Module*)this->Creator, this, ServerInstance, L.IPAddr, L);
3956                                                 ServerInstance->AddResolver(sr);
3957                                         }
3958                                         catch (ModuleException& e)
3959                                         {
3960                                                 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
3961                                         }
3962                                 }
3963
3964                                 LinkBlocks.push_back(L);
3965                                 ServerInstance->Log(DEBUG,"m_spanningtree: Read server %s with host %s:%d",L.Name.c_str(),L.IPAddr.c_str(),L.Port);
3966                         }
3967                         else
3968                         {
3969                                 if (L.IPAddr == "")
3970                                 {
3971                                         ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', IP address not defined!",L.Name.c_str());
3972                                 }
3973                                 else if (L.RecvPass == "")
3974                                 {
3975                                         ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', recvpass not defined!",L.Name.c_str());
3976                                 }
3977                                 else if (L.SendPass == "")
3978                                 {
3979                                         ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', sendpass not defined!",L.Name.c_str());
3980                                 }
3981                                 else if (L.Name == "")
3982                                 {
3983                                         ServerInstance->Log(DEFAULT,"Invalid configuration, link tag without a name!");
3984                                 }
3985                                 else if (!L.Port)
3986                                 {
3987                                         ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', no port specified!",L.Name.c_str());
3988                                 }
3989                         }
3990                 }
3991                 else
3992                 {
3993                         ServerInstance->Log(DEFAULT,"Invalid configuration for server '%s', link tag has the same server name as the local server!",L.Name.c_str());
3994                 }
3995         }
3996         DELETE(Conf);
3997 }
3998
3999 /** To create a timer which recurs every second, we inherit from InspTimer.
4000  * InspTimer is only one-shot however, so at the end of each Tick() we simply
4001  * insert another of ourselves into the pending queue :)
4002  */
4003 class TimeSyncTimer : public InspTimer
4004 {
4005  private:
4006         InspIRCd *Instance;
4007         ModuleSpanningTree *Module;
4008  public:
4009         TimeSyncTimer(InspIRCd *Instance, ModuleSpanningTree *Mod);
4010         virtual void Tick(time_t TIME);
4011 };
4012
4013 class ModuleSpanningTree : public Module
4014 {
4015         int line;
4016         int NumServers;
4017         unsigned int max_local;
4018         unsigned int max_global;
4019         cmd_rconnect* command_rconnect;
4020         SpanningTreeUtilities* Utils;
4021
4022  public:
4023         TimeSyncTimer *SyncTimer;
4024
4025         ModuleSpanningTree(InspIRCd* Me)
4026                 : Module::Module(Me), max_local(0), max_global(0)
4027         {
4028                 Utils = new SpanningTreeUtilities(Me, this);
4029
4030                 command_rconnect = new cmd_rconnect(ServerInstance, this, Utils);
4031                 ServerInstance->AddCommand(command_rconnect);
4032
4033                 if (Utils->EnableTimeSync)
4034                 {
4035                         SyncTimer = new TimeSyncTimer(ServerInstance, this);
4036                         ServerInstance->Timers->AddTimer(SyncTimer);
4037                 }
4038                 else
4039                         SyncTimer = NULL;
4040         }
4041
4042         void ShowLinks(TreeServer* Current, userrec* user, int hops)
4043         {
4044                 std::string Parent = Utils->TreeRoot->GetName();
4045                 if (Current->GetParent())
4046                 {
4047                         Parent = Current->GetParent()->GetName();
4048                 }
4049                 for (unsigned int q = 0; q < Current->ChildCount(); q++)
4050                 {
4051                         if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str())))
4052                         {
4053                                 if (*user->oper)
4054                                 {
4055                                          ShowLinks(Current->GetChild(q),user,hops+1);
4056                                 }
4057                         }
4058                         else
4059                         {
4060                                 ShowLinks(Current->GetChild(q),user,hops+1);
4061                         }
4062                 }
4063                 /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
4064                 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetName().c_str())) && (!*user->oper))
4065                         return;
4066                 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());
4067         }
4068
4069         int CountLocalServs()
4070         {
4071                 return Utils->TreeRoot->ChildCount();
4072         }
4073
4074         int CountServs()
4075         {
4076                 return Utils->serverlist.size();
4077         }
4078
4079         void HandleLinks(const char** parameters, int pcnt, userrec* user)
4080         {
4081                 ShowLinks(Utils->TreeRoot,user,0);
4082                 user->WriteServ("365 %s * :End of /LINKS list.",user->nick);
4083                 return;
4084         }
4085
4086         void HandleLusers(const char** parameters, int pcnt, userrec* user)
4087         {
4088                 unsigned int n_users = ServerInstance->UserCount();
4089
4090                 /* Only update these when someone wants to see them, more efficient */
4091                 if ((unsigned int)ServerInstance->LocalUserCount() > max_local)
4092                         max_local = ServerInstance->LocalUserCount();
4093                 if (n_users > max_global)
4094                         max_global = n_users;
4095
4096                 user->WriteServ("251 %s :There are %d users and %d invisible on %d servers",user->nick,n_users-ServerInstance->InvisibleUserCount(),ServerInstance->InvisibleUserCount(),this->CountServs());
4097                 if (ServerInstance->OperCount())
4098                         user->WriteServ("252 %s %d :operator(s) online",user->nick,ServerInstance->OperCount());
4099                 if (ServerInstance->UnregisteredUserCount())
4100                         user->WriteServ("253 %s %d :unknown connections",user->nick,ServerInstance->UnregisteredUserCount());
4101                 if (ServerInstance->ChannelCount())
4102                         user->WriteServ("254 %s %d :channels formed",user->nick,ServerInstance->ChannelCount());
4103                 user->WriteServ("254 %s :I have %d clients and %d servers",user->nick,ServerInstance->LocalUserCount(),this->CountLocalServs());
4104                 user->WriteServ("265 %s :Current Local Users: %d  Max: %d",user->nick,ServerInstance->LocalUserCount(),max_local);
4105                 user->WriteServ("266 %s :Current Global Users: %d  Max: %d",user->nick,n_users,max_global);
4106                 return;
4107         }
4108
4109         // WARNING: NOT THREAD SAFE - DONT GET ANY SMART IDEAS.
4110
4111         void ShowMap(TreeServer* Current, userrec* user, int depth, char matrix[128][80], float &totusers, float &totservers)
4112         {
4113                 if (line < 128)
4114                 {
4115                         for (int t = 0; t < depth; t++)
4116                         {
4117                                 matrix[line][t] = ' ';
4118                         }
4119
4120                         // For Aligning, we need to work out exactly how deep this thing is, and produce
4121                         // a 'Spacer' String to compensate.
4122                         char spacer[40];
4123
4124                         memset(spacer,' ',40);
4125                         if ((40 - Current->GetName().length() - depth) > 1) {
4126                                 spacer[40 - Current->GetName().length() - depth] = '\0';
4127                         }
4128                         else
4129                         {
4130                                 spacer[5] = '\0';
4131                         }
4132
4133                         float percent;
4134                         char text[80];
4135                         if (ServerInstance->clientlist.size() == 0) {
4136                                 // If there are no users, WHO THE HELL DID THE /MAP?!?!?!
4137                                 percent = 0;
4138                         }
4139                         else
4140                         {
4141                                 percent = ((float)Current->GetUserCount() / (float)ServerInstance->clientlist.size()) * 100;
4142                         }
4143                         snprintf(text, 80, "%s %s%5d [%5.2f%%]", Current->GetName().c_str(), spacer, Current->GetUserCount(), percent);
4144                         totusers += Current->GetUserCount();
4145                         totservers++;
4146                         strlcpy(&matrix[line][depth],text,80);
4147                         line++;
4148                         for (unsigned int q = 0; q < Current->ChildCount(); q++)
4149                         {
4150                                 if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str())))
4151                                 {
4152                                         if (*user->oper)
4153                                         {
4154                                                 ShowMap(Current->GetChild(q),user,(Utils->FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
4155                                         }
4156                                 }
4157                                 else
4158                                 {
4159                                         ShowMap(Current->GetChild(q),user,(Utils->FlatLinks && (!*user->oper)) ? depth : depth+2,matrix,totusers,totservers);
4160                                 }
4161                         }
4162                 }
4163         }
4164
4165         int HandleMotd(const char** parameters, int pcnt, userrec* user)
4166         {
4167                 if (pcnt > 0)
4168                 {
4169                         /* Remote MOTD, the server is within the 1st parameter */
4170                         std::deque<std::string> params;
4171                         params.push_back(parameters[0]);
4172
4173                         /* Send it out remotely, generate no reply yet */
4174                         TreeServer* s = Utils->FindServerMask(parameters[0]);
4175                         if (s)
4176                         {
4177                                 Utils->DoOneToOne(user->nick, "MOTD", params, s->GetName());
4178                         }
4179                         else
4180                         {
4181                                 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4182                         }
4183                         return 1;
4184                 }
4185                 return 0;
4186         }
4187
4188         int HandleAdmin(const char** parameters, int pcnt, userrec* user)
4189         {
4190                 if (pcnt > 0)
4191                 {
4192                         /* Remote ADMIN, the server is within the 1st parameter */
4193                         std::deque<std::string> params;
4194                         params.push_back(parameters[0]);
4195
4196                         /* Send it out remotely, generate no reply yet */
4197                         TreeServer* s = Utils->FindServerMask(parameters[0]);
4198                         if (s)
4199                         {
4200                                 Utils->DoOneToOne(user->nick, "ADMIN", params, s->GetName());
4201                         }
4202                         else
4203                         {
4204                                 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4205                         }
4206                         return 1;
4207                 }
4208                 return 0;
4209         }
4210
4211         int HandleStats(const char** parameters, int pcnt, userrec* user)
4212         {
4213                 if (pcnt > 1)
4214                 {
4215                         /* Remote STATS, the server is within the 2nd parameter */
4216                         std::deque<std::string> params;
4217                         params.push_back(parameters[0]);
4218                         params.push_back(parameters[1]);
4219                         /* Send it out remotely, generate no reply yet */
4220                         TreeServer* s = Utils->FindServerMask(parameters[1]);
4221                         if (s)
4222                         {
4223                                 params[1] = s->GetName();
4224                                 Utils->DoOneToOne(user->nick, "STATS", params, s->GetName());
4225                         }
4226                         else
4227                         {
4228                                 user->WriteServ( "402 %s %s :No such server", user->nick, parameters[0]);
4229                         }
4230                         return 1;
4231                 }
4232                 return 0;
4233         }
4234
4235         // Ok, prepare to be confused.
4236         // After much mulling over how to approach this, it struck me that
4237         // the 'usual' way of doing a /MAP isnt the best way. Instead of
4238         // keeping track of a ton of ascii characters, and line by line
4239         // under recursion working out where to place them using multiplications
4240         // and divisons, we instead render the map onto a backplane of characters
4241         // (a character matrix), then draw the branches as a series of "L" shapes
4242         // from the nodes. This is not only friendlier on CPU it uses less stack.
4243
4244         void HandleMap(const char** parameters, int pcnt, userrec* user)
4245         {
4246                 // This array represents a virtual screen which we will
4247                 // "scratch" draw to, as the console device of an irc
4248                 // client does not provide for a proper terminal.
4249                 float totusers = 0;
4250                 float totservers = 0;
4251                 char matrix[128][80];
4252                 for (unsigned int t = 0; t < 128; t++)
4253                 {
4254                         matrix[t][0] = '\0';
4255                 }
4256                 line = 0;
4257                 // The only recursive bit is called here.
4258                 ShowMap(Utils->TreeRoot,user,0,matrix,totusers,totservers);
4259                 // Process each line one by one. The algorithm has a limit of
4260                 // 128 servers (which is far more than a spanning tree should have
4261                 // anyway, so we're ok). This limit can be raised simply by making
4262                 // the character matrix deeper, 128 rows taking 10k of memory.
4263                 for (int l = 1; l < line; l++)
4264                 {
4265                         // scan across the line looking for the start of the
4266                         // servername (the recursive part of the algorithm has placed
4267                         // the servers at indented positions depending on what they
4268                         // are related to)
4269                         int first_nonspace = 0;
4270                         while (matrix[l][first_nonspace] == ' ')
4271                         {
4272                                 first_nonspace++;
4273                         }
4274                         first_nonspace--;
4275                         // Draw the `- (corner) section: this may be overwritten by
4276                         // another L shape passing along the same vertical pane, becoming
4277                         // a |- (branch) section instead.
4278                         matrix[l][first_nonspace] = '-';
4279                         matrix[l][first_nonspace-1] = '`';
4280                         int l2 = l - 1;
4281                         // Draw upwards until we hit the parent server, causing possibly
4282                         // other corners (`-) to become branches (|-)
4283                         while ((matrix[l2][first_nonspace-1] == ' ') || (matrix[l2][first_nonspace-1] == '`'))
4284                         {
4285                                 matrix[l2][first_nonspace-1] = '|';
4286                                 l2--;
4287                         }
4288                 }
4289                 // dump the whole lot to the user. This is the easy bit, honest.
4290                 for (int t = 0; t < line; t++)
4291                 {
4292                         user->WriteServ("006 %s :%s",user->nick,&matrix[t][0]);
4293                 }
4294                 float avg_users = totusers / totservers;
4295                 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);
4296         user->WriteServ("007 %s :End of /MAP",user->nick);
4297                 return;
4298         }
4299
4300         int HandleSquit(const char** parameters, int pcnt, userrec* user)
4301         {
4302                 TreeServer* s = Utils->FindServerMask(parameters[0]);
4303                 if (s)
4304                 {
4305                         if (s == Utils->TreeRoot)
4306                         {
4307                                  user->WriteServ("NOTICE %s :*** SQUIT: Foolish mortal, you cannot make a server SQUIT itself! (%s matches local server name)",user->nick,parameters[0]);
4308                                 return 1;
4309                         }
4310                         TreeSocket* sock = s->GetSocket();
4311                         if (sock)
4312                         {
4313                                 ServerInstance->Log(DEBUG,"Splitting server %s",s->GetName().c_str());
4314                                 ServerInstance->SNO->WriteToSnoMask('l',"SQUIT: Server \002%s\002 removed from network by %s",parameters[0],user->nick);
4315                                 sock->Squit(s,"Server quit by "+std::string(user->nick)+"!"+std::string(user->ident)+"@"+std::string(user->host));
4316                                 ServerInstance->SE->DelFd(sock);
4317                                 sock->Close();
4318                                 delete sock;
4319                         }
4320                         else
4321                         {
4322                                 user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 is not directly connected.",user->nick,parameters[0]);
4323                         }
4324                 }
4325                 else
4326                 {
4327                          user->WriteServ("NOTICE %s :*** SQUIT: The server \002%s\002 does not exist on the network.",user->nick,parameters[0]);
4328                 }
4329                 return 1;
4330         }
4331
4332         int HandleTime(const char** parameters, int pcnt, userrec* user)
4333         {
4334                 if ((IS_LOCAL(user)) && (pcnt))
4335                 {
4336                         TreeServer* found = Utils->FindServerMask(parameters[0]);
4337                         if (found)
4338                         {
4339                                 // we dont' override for local server
4340                                 if (found == Utils->TreeRoot)
4341                                         return 0;
4342                                 
4343                                 std::deque<std::string> params;
4344                                 params.push_back(found->GetName());
4345                                 params.push_back(user->nick);
4346                                 Utils->DoOneToOne(ServerInstance->Config->ServerName,"TIME",params,found->GetName());
4347                         }
4348                         else
4349                         {
4350                                 user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
4351                         }
4352                 }
4353                 return 1;
4354         }
4355
4356         int HandleRemoteWhois(const char** parameters, int pcnt, userrec* user)
4357         {
4358                 if ((IS_LOCAL(user)) && (pcnt > 1))
4359                 {
4360                         userrec* remote = ServerInstance->FindNick(parameters[1]);
4361                         if ((remote) && (remote->GetFd() < 0))
4362                         {
4363                                 std::deque<std::string> params;
4364                                 params.push_back(parameters[1]);
4365                                 Utils->DoOneToOne(user->nick,"IDLE",params,remote->server);
4366                                 return 1;
4367                         }
4368                         else if (!remote)
4369                         {
4370                                 user->WriteServ("401 %s %s :No such nick/channel",user->nick, parameters[1]);
4371                                 user->WriteServ("318 %s %s :End of /WHOIS list.",user->nick, parameters[1]);
4372                                 return 1;
4373                         }
4374                 }
4375                 return 0;
4376         }
4377
4378         void DoPingChecks(time_t curtime)
4379         {
4380                 for (unsigned int j = 0; j < Utils->TreeRoot->ChildCount(); j++)
4381                 {
4382                         TreeServer* serv = Utils->TreeRoot->GetChild(j);
4383                         TreeSocket* sock = serv->GetSocket();
4384                         if (sock)
4385                         {
4386                                 if (curtime >= serv->NextPingTime())
4387                                 {
4388                                         if (serv->AnsweredLastPing())
4389                                         {
4390                                                 sock->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" PING "+serv->GetName());
4391                                                 serv->SetNextPingTime(curtime + 60);
4392                                         }
4393                                         else
4394                                         {
4395                                                 // they didnt answer, boot them
4396                                                 ServerInstance->SNO->WriteToSnoMask('l',"Server \002%s\002 pinged out",serv->GetName().c_str());
4397                                                 sock->Squit(serv,"Ping timeout");
4398                                                 ServerInstance->SE->DelFd(sock);
4399                                                 sock->Close();
4400                                                 delete sock;
4401                                                 return;
4402                                         }
4403                                 }
4404                         }
4405                 }
4406         }
4407
4408         void ConnectServer(Link* x)
4409         {
4410                 insp_inaddr binip;
4411
4412                 /* Do we already have an IP? If so, no need to resolve it. */
4413                 if (insp_aton(x->IPAddr.c_str(), &binip) > 0)
4414                 {
4415                         TreeSocket* newsocket = new TreeSocket(Utils, ServerInstance, x->IPAddr,x->Port,false,x->Timeout ? x->Timeout : 10,x->Name.c_str());
4416                         if (newsocket->GetFd() > -1)
4417                         {
4418                                 /* Handled automatically on success */
4419                         }
4420                         else
4421                         {
4422                                 ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
4423                                 delete newsocket;
4424                                 Utils->DoFailOver(x);
4425                         }
4426                 }
4427                 else
4428                 {
4429                         try
4430                         {
4431                                 ServernameResolver* snr = new ServernameResolver((Module*)this, Utils, ServerInstance,x->IPAddr, *x);
4432                                 ServerInstance->AddResolver(snr);
4433                         }
4434                         catch (ModuleException& e)
4435                         {
4436                                 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
4437                                 Utils->DoFailOver(x);
4438                         }
4439                 }
4440         }
4441
4442         void AutoConnectServers(time_t curtime)
4443         {
4444                 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
4445                 {
4446                         if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
4447                         {
4448                                 ServerInstance->Log(DEBUG,"Auto-Connecting %s",x->Name.c_str());
4449                                 x->NextConnectTime = curtime + x->AutoConnect;
4450                                 TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
4451                                 if (x->FailOver.length())
4452                                 {
4453                                         TreeServer* CheckFailOver = Utils->FindServer(x->FailOver.c_str());
4454                                         if (CheckFailOver)
4455                                         {
4456                                                 /* The failover for this server is currently a member of the network.
4457                                                  * The failover probably succeeded, where the main link did not.
4458                                                  * Don't try the main link until the failover is gone again.
4459                                                  */
4460                                                 continue;
4461                                         }
4462                                 }
4463                                 if (!CheckDupe)
4464                                 {
4465                                         // an autoconnected server is not connected. Check if its time to connect it
4466                                         ServerInstance->SNO->WriteToSnoMask('l',"AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
4467                                         this->ConnectServer(&(*x));
4468                                 }
4469                         }
4470                 }
4471         }
4472
4473         int HandleVersion(const char** parameters, int pcnt, userrec* user)
4474         {
4475                 // we've already checked if pcnt > 0, so this is safe
4476                 TreeServer* found = Utils->FindServerMask(parameters[0]);
4477                 if (found)
4478                 {
4479                         std::string Version = found->GetVersion();
4480                         user->WriteServ("351 %s :%s",user->nick,Version.c_str());
4481                         if (found == Utils->TreeRoot)
4482                         {
4483                                 std::stringstream out(ServerInstance->Config->data005);
4484                                 std::string token = "";
4485                                 std::string line5 = "";
4486                                 int token_counter = 0;
4487
4488                                 while (!out.eof())
4489                                 {
4490                                         out >> token;
4491                                         line5 = line5 + token + " ";   
4492                                         token_counter++;
4493
4494                                         if ((token_counter >= 13) || (out.eof() == true))
4495                                         {
4496                                                 user->WriteServ("005 %s %s:are supported by this server",user->nick,line5.c_str());
4497                                                 line5 = "";
4498                                                 token_counter = 0;
4499                                         }
4500                                 }
4501                         }
4502                 }
4503                 else
4504                 {
4505                         user->WriteServ("402 %s %s :No such server",user->nick,parameters[0]);
4506                 }
4507                 return 1;
4508         }
4509         
4510         int HandleConnect(const char** parameters, int pcnt, userrec* user)
4511         {
4512                 for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
4513                 {
4514                         if (ServerInstance->MatchText(x->Name.c_str(),parameters[0]))
4515                         {
4516                                 TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
4517                                 if (!CheckDupe)
4518                                 {
4519                                         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);
4520                                         ConnectServer(&(*x));
4521                                         return 1;
4522                                 }
4523                                 else
4524                                 {
4525                                         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());
4526                                         return 1;
4527                                 }
4528                         }
4529                 }
4530                 user->WriteServ("NOTICE %s :*** CONNECT: No server matching \002%s\002 could be found in the config file.",user->nick,parameters[0]);
4531                 return 1;
4532         }
4533
4534         void BroadcastTimeSync()
4535         {
4536                 std::deque<std::string> params;
4537                 params.push_back(ConvToStr(ServerInstance->Time(true)));
4538                 Utils->DoOneToMany(Utils->TreeRoot->GetName(), "TIMESET", params);
4539         }
4540
4541         virtual int OnStats(char statschar, userrec* user, string_list &results)
4542         {
4543                 if (statschar == 'c')
4544                 {
4545                         for (unsigned int i = 0; i < Utils->LinkBlocks.size(); i++)
4546                         {
4547                                 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');
4548                                 results.push_back(std::string(ServerInstance->Config->ServerName)+" 244 "+user->nick+" H * * "+Utils->LinkBlocks[i].Name.c_str());
4549                         }
4550                         results.push_back(std::string(ServerInstance->Config->ServerName)+" 219 "+user->nick+" "+statschar+" :End of /STATS report");
4551                         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);
4552                         return 1;
4553                 }
4554                 return 0;
4555         }
4556
4557         virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated, const std::string &original_line)
4558         {
4559                 /* If the command doesnt appear to be valid, we dont want to mess with it. */
4560                 if (!validated)
4561                         return 0;
4562
4563                 if (command == "CONNECT")
4564                 {
4565                         return this->HandleConnect(parameters,pcnt,user);
4566                 }
4567                 else if (command == "STATS")
4568                 {
4569                         return this->HandleStats(parameters,pcnt,user);
4570                 }
4571                 else if (command == "MOTD")
4572                 {
4573                         return this->HandleMotd(parameters,pcnt,user);
4574                 }
4575                 else if (command == "ADMIN")
4576                 {
4577                         return this->HandleAdmin(parameters,pcnt,user);
4578                 }
4579                 else if (command == "SQUIT")
4580                 {
4581                         return this->HandleSquit(parameters,pcnt,user);
4582                 }
4583                 else if (command == "MAP")
4584                 {
4585                         this->HandleMap(parameters,pcnt,user);
4586                         return 1;
4587                 }
4588                 else if ((command == "TIME") && (pcnt > 0))
4589                 {
4590                         return this->HandleTime(parameters,pcnt,user);
4591                 }
4592                 else if (command == "LUSERS")
4593                 {
4594                         this->HandleLusers(parameters,pcnt,user);
4595                         return 1;
4596                 }
4597                 else if (command == "LINKS")
4598                 {
4599                         this->HandleLinks(parameters,pcnt,user);
4600                         return 1;
4601                 }
4602                 else if (command == "WHOIS")
4603                 {
4604                         if (pcnt > 1)
4605                         {
4606                                 // remote whois
4607                                 return this->HandleRemoteWhois(parameters,pcnt,user);
4608                         }
4609                 }
4610                 else if ((command == "VERSION") && (pcnt > 0))
4611                 {
4612                         this->HandleVersion(parameters,pcnt,user);
4613                         return 1;
4614                 }
4615
4616                 return 0;
4617         }
4618
4619         virtual void OnPostCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, CmdResult result, const std::string &original_line)
4620         {
4621                 if ((result == CMD_SUCCESS) && (ServerInstance->IsValidModuleCommand(command, pcnt, user)))
4622                 {
4623                         // this bit of code cleverly routes all module commands
4624                         // to all remote severs *automatically* so that modules
4625                         // can just handle commands locally, without having
4626                         // to have any special provision in place for remote
4627                         // commands and linking protocols.
4628                         std::deque<std::string> params;
4629                         params.clear();
4630                         for (int j = 0; j < pcnt; j++)
4631                         {
4632                                 if (strchr(parameters[j],' '))
4633                                 {
4634                                         params.push_back(":" + std::string(parameters[j]));
4635                                 }
4636                                 else
4637                                 {
4638                                         params.push_back(std::string(parameters[j]));
4639                                 }
4640                         }
4641                         ServerInstance->Log(DEBUG,"Globally route '%s'",command.c_str());
4642                         Utils->DoOneToMany(user->nick,command,params);
4643                 }
4644         }
4645
4646         virtual void OnGetServerDescription(const std::string &servername,std::string &description)
4647         {
4648                 TreeServer* s = Utils->FindServer(servername);
4649                 if (s)
4650                 {
4651                         description = s->GetDesc();
4652                 }
4653         }
4654
4655         virtual void OnUserInvite(userrec* source,userrec* dest,chanrec* channel)
4656         {
4657                 if (IS_LOCAL(source))
4658                 {
4659                         std::deque<std::string> params;
4660                         params.push_back(dest->nick);
4661                         params.push_back(channel->name);
4662                         Utils->DoOneToMany(source->nick,"INVITE",params);
4663                 }
4664         }
4665
4666         virtual void OnPostLocalTopicChange(userrec* user, chanrec* chan, const std::string &topic)
4667         {
4668                 std::deque<std::string> params;
4669                 params.push_back(chan->name);
4670                 params.push_back(":"+topic);
4671                 Utils->DoOneToMany(user->nick,"TOPIC",params);
4672         }
4673
4674         virtual void OnWallops(userrec* user, const std::string &text)
4675         {
4676                 if (IS_LOCAL(user))
4677                 {
4678                         std::deque<std::string> params;
4679                         params.push_back(":"+text);
4680                         Utils->DoOneToMany(user->nick,"WALLOPS",params);
4681                 }
4682         }
4683
4684         virtual void OnUserNotice(userrec* user, void* dest, int target_type, const std::string &text, char status)
4685         {
4686                 if (target_type == TYPE_USER)
4687                 {
4688                         userrec* d = (userrec*)dest;
4689                         if ((d->GetFd() < 0) && (IS_LOCAL(user)))
4690                         {
4691                                 std::deque<std::string> params;
4692                                 params.clear();
4693                                 params.push_back(d->nick);
4694                                 params.push_back(":"+text);
4695                                 Utils->DoOneToOne(user->nick,"NOTICE",params,d->server);
4696                         }
4697                 }
4698                 else if (target_type == TYPE_CHANNEL)
4699                 {
4700                         if (IS_LOCAL(user))
4701                         {
4702                                 chanrec *c = (chanrec*)dest;
4703                                 if (c)
4704                                 {
4705                                         std::string cname = c->name;
4706                                         if (status)
4707                                                 cname = status + cname;
4708                                         std::deque<TreeServer*> list;
4709                                         Utils->GetListOfServersForChannel(c,list);
4710                                         unsigned int ucount = list.size();
4711                                         for (unsigned int i = 0; i < ucount; i++)
4712                                         {
4713                                                 TreeSocket* Sock = list[i]->GetSocket();
4714                                                 if (Sock)
4715                                                         Sock->WriteLine(":"+std::string(user->nick)+" NOTICE "+cname+" :"+text);
4716                                         }
4717                                 }
4718                         }
4719                 }
4720                 else if (target_type == TYPE_SERVER)
4721                 {
4722                         if (IS_LOCAL(user))
4723                         {
4724                                 char* target = (char*)dest;
4725                                 std::deque<std::string> par;
4726                                 par.push_back(target);
4727                                 par.push_back(":"+text);
4728                                 Utils->DoOneToMany(user->nick,"NOTICE",par);
4729                         }
4730                 }
4731         }
4732
4733         virtual void OnUserMessage(userrec* user, void* dest, int target_type, const std::string &text, char status)
4734         {
4735                 if (target_type == TYPE_USER)
4736                 {
4737                         // route private messages which are targetted at clients only to the server
4738                         // which needs to receive them
4739                         userrec* d = (userrec*)dest;
4740                         if ((d->GetFd() < 0) && (IS_LOCAL(user)))
4741                         {
4742                                 std::deque<std::string> params;
4743                                 params.clear();
4744                                 params.push_back(d->nick);
4745                                 params.push_back(":"+text);
4746                                 Utils->DoOneToOne(user->nick,"PRIVMSG",params,d->server);
4747                         }
4748                 }
4749                 else if (target_type == TYPE_CHANNEL)
4750                 {
4751                         if (IS_LOCAL(user))
4752                         {
4753                                 chanrec *c = (chanrec*)dest;
4754                                 if (c)
4755                                 {
4756                                         std::string cname = c->name;
4757                                         if (status)
4758                                                 cname = status + cname;
4759                                         std::deque<TreeServer*> list;
4760                                         Utils->GetListOfServersForChannel(c,list);
4761                                         unsigned int ucount = list.size();
4762                                         for (unsigned int i = 0; i < ucount; i++)
4763                                         {
4764                                                 TreeSocket* Sock = list[i]->GetSocket();
4765                                                 if (Sock)
4766                                                         Sock->WriteLine(":"+std::string(user->nick)+" PRIVMSG "+cname+" :"+text);
4767                                         }
4768                                 }
4769                         }
4770                 }
4771                 else if (target_type == TYPE_SERVER)
4772                 {
4773                         if (IS_LOCAL(user))
4774                         {
4775                                 char* target = (char*)dest;
4776                                 std::deque<std::string> par;
4777                                 par.push_back(target);
4778                                 par.push_back(":"+text);
4779                                 Utils->DoOneToMany(user->nick,"PRIVMSG",par);
4780                         }
4781                 }
4782         }
4783
4784         virtual void OnBackgroundTimer(time_t curtime)
4785         {
4786                 AutoConnectServers(curtime);
4787                 DoPingChecks(curtime);
4788         }
4789
4790         virtual void OnUserJoin(userrec* user, chanrec* channel)
4791         {
4792                 // Only do this for local users
4793                 if (IS_LOCAL(user))
4794                 {
4795                         std::deque<std::string> params;
4796                         params.clear();
4797                         params.push_back(channel->name);
4798                         // set up their permissions and the channel TS with FJOIN.
4799                         // All users are FJOINed now, because a module may specify
4800                         // new joining permissions for the user.
4801                         params.clear();
4802                         params.push_back(channel->name);
4803                         params.push_back(ConvToStr(channel->age));
4804                         params.push_back(std::string(channel->GetAllPrefixChars(user))+","+std::string(user->nick));
4805                         Utils->DoOneToMany(ServerInstance->Config->ServerName,"FJOIN",params);
4806                 }
4807         }
4808
4809         virtual void OnChangeHost(userrec* user, const std::string &newhost)
4810         {
4811                 // only occurs for local clients
4812                 if (user->registered != REG_ALL)
4813                         return;
4814                 std::deque<std::string> params;
4815                 params.push_back(newhost);
4816                 Utils->DoOneToMany(user->nick,"FHOST",params);
4817         }
4818
4819         virtual void OnChangeName(userrec* user, const std::string &gecos)
4820         {
4821                 // only occurs for local clients
4822                 if (user->registered != REG_ALL)
4823                         return;
4824                 std::deque<std::string> params;
4825                 params.push_back(gecos);
4826                 Utils->DoOneToMany(user->nick,"FNAME",params);
4827         }
4828
4829         virtual void OnUserPart(userrec* user, chanrec* channel, const std::string &partmessage)
4830         {
4831                 if (IS_LOCAL(user))
4832                 {
4833                         std::deque<std::string> params;
4834                         params.push_back(channel->name);
4835                         if (partmessage != "")
4836                                 params.push_back(":"+partmessage);
4837                         Utils->DoOneToMany(user->nick,"PART",params);
4838                 }
4839         }
4840
4841         virtual void OnUserConnect(userrec* user)
4842         {
4843                 char agestr[MAXBUF];
4844                 if (IS_LOCAL(user))
4845                 {
4846                         std::deque<std::string> params;
4847                         snprintf(agestr,MAXBUF,"%lu",(unsigned long)user->age);
4848                         params.push_back(agestr);
4849                         params.push_back(user->nick);
4850                         params.push_back(user->host);
4851                         params.push_back(user->dhost);
4852                         params.push_back(user->ident);
4853                         params.push_back("+"+std::string(user->FormatModes()));
4854                         params.push_back(user->GetIPString());
4855                         params.push_back(":"+std::string(user->fullname));
4856                         Utils->DoOneToMany(ServerInstance->Config->ServerName,"NICK",params);
4857
4858                         // User is Local, change needs to be reflected!
4859                         TreeServer* SourceServer = Utils->FindServer(user->server);
4860                         if (SourceServer)
4861                         {
4862                                 SourceServer->AddUserCount();
4863                         }
4864
4865                 }
4866         }
4867
4868         virtual void OnUserQuit(userrec* user, const std::string &reason)
4869         {
4870                 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
4871                 {
4872                         std::deque<std::string> params;
4873                         params.push_back(":"+reason);
4874                         Utils->DoOneToMany(user->nick,"QUIT",params);
4875                 }
4876                 // Regardless, We need to modify the user Counts..
4877                 TreeServer* SourceServer = Utils->FindServer(user->server);
4878                 if (SourceServer)
4879                 {
4880                         SourceServer->DelUserCount();
4881                 }
4882
4883         }
4884
4885         virtual void OnUserPostNick(userrec* user, const std::string &oldnick)
4886         {
4887                 if (IS_LOCAL(user))
4888                 {
4889                         std::deque<std::string> params;
4890                         params.push_back(user->nick);
4891                         Utils->DoOneToMany(oldnick,"NICK",params);
4892                 }
4893         }
4894
4895         virtual void OnUserKick(userrec* source, userrec* user, chanrec* chan, const std::string &reason)
4896         {
4897                 if ((source) && (IS_LOCAL(source)))
4898                 {
4899                         std::deque<std::string> params;
4900                         params.push_back(chan->name);
4901                         params.push_back(user->nick);
4902                         params.push_back(":"+reason);
4903                         Utils->DoOneToMany(source->nick,"KICK",params);
4904                 }
4905                 else if (!source)
4906                 {
4907                         std::deque<std::string> params;
4908                         params.push_back(chan->name);
4909                         params.push_back(user->nick);
4910                         params.push_back(":"+reason);
4911                         Utils->DoOneToMany(ServerInstance->Config->ServerName,"KICK",params);
4912                 }
4913         }
4914
4915         virtual void OnRemoteKill(userrec* source, userrec* dest, const std::string &reason)
4916         {
4917                 std::deque<std::string> params;
4918                 params.push_back(dest->nick);
4919                 params.push_back(":"+reason);
4920                 Utils->DoOneToMany(source->nick,"KILL",params);
4921         }
4922
4923         virtual void OnRehash(const std::string &parameter)
4924         {
4925                 if (parameter != "")
4926                 {
4927                         std::deque<std::string> params;
4928                         params.push_back(parameter);
4929                         Utils->DoOneToMany(ServerInstance->Config->ServerName,"REHASH",params);
4930                         // check for self
4931                         if (ServerInstance->MatchText(ServerInstance->Config->ServerName,parameter))
4932                         {
4933                                 ServerInstance->WriteOpers("*** Remote rehash initiated from server \002%s\002",ServerInstance->Config->ServerName);
4934                                 ServerInstance->RehashServer();
4935                         }
4936                 }
4937                 Utils->ReadConfiguration(false);
4938         }
4939
4940         // note: the protocol does not allow direct umode +o except
4941         // via NICK with 8 params. sending OPERTYPE infers +o modechange
4942         // locally.
4943         virtual void OnOper(userrec* user, const std::string &opertype)
4944         {
4945                 if (IS_LOCAL(user))
4946                 {
4947                         std::deque<std::string> params;
4948                         params.push_back(opertype);
4949                         Utils->DoOneToMany(user->nick,"OPERTYPE",params);
4950                 }
4951         }
4952
4953         void OnLine(userrec* source, const std::string &host, bool adding, char linetype, long duration, const std::string &reason)
4954         {
4955                 if (!source)
4956                 {
4957                         /* Server-set lines */
4958                         char data[MAXBUF];
4959                         snprintf(data,MAXBUF,"%c %s %s %lu %lu :%s", linetype, host.c_str(), ServerInstance->Config->ServerName, (unsigned long)ServerInstance->Time(false),
4960                                         (unsigned long)duration, reason.c_str());
4961                         std::deque<std::string> params;
4962                         params.push_back(data);
4963                         Utils->DoOneToMany(ServerInstance->Config->ServerName, "ADDLINE", params);
4964                 }
4965                 else
4966                 {
4967                         if (IS_LOCAL(source))
4968                         {
4969                                 char type[8];
4970                                 snprintf(type,8,"%cLINE",linetype);
4971                                 std::string stype = type;
4972                                 if (adding)
4973                                 {
4974                                         char sduration[MAXBUF];
4975                                         snprintf(sduration,MAXBUF,"%ld",duration);
4976                                         std::deque<std::string> params;
4977                                         params.push_back(host);
4978                                         params.push_back(sduration);
4979                                         params.push_back(":"+reason);
4980                                         Utils->DoOneToMany(source->nick,stype,params);
4981                                 }
4982                                 else
4983                                 {
4984                                         std::deque<std::string> params;
4985                                         params.push_back(host);
4986                                         Utils->DoOneToMany(source->nick,stype,params);
4987                                 }
4988                         }
4989                 }
4990         }
4991
4992         virtual void OnAddGLine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
4993         {
4994                 OnLine(source,hostmask,true,'G',duration,reason);
4995         }
4996         
4997         virtual void OnAddZLine(long duration, userrec* source, const std::string &reason, const std::string &ipmask)
4998         {
4999                 OnLine(source,ipmask,true,'Z',duration,reason);
5000         }
5001
5002         virtual void OnAddQLine(long duration, userrec* source, const std::string &reason, const std::string &nickmask)
5003         {
5004                 OnLine(source,nickmask,true,'Q',duration,reason);
5005         }
5006
5007         virtual void OnAddELine(long duration, userrec* source, const std::string &reason, const std::string &hostmask)
5008         {
5009                 OnLine(source,hostmask,true,'E',duration,reason);
5010         }
5011
5012         virtual void OnDelGLine(userrec* source, const std::string &hostmask)
5013         {
5014                 OnLine(source,hostmask,false,'G',0,"");
5015         }
5016
5017         virtual void OnDelZLine(userrec* source, const std::string &ipmask)
5018         {
5019                 OnLine(source,ipmask,false,'Z',0,"");
5020         }
5021
5022         virtual void OnDelQLine(userrec* source, const std::string &nickmask)
5023         {
5024                 OnLine(source,nickmask,false,'Q',0,"");
5025         }
5026
5027         virtual void OnDelELine(userrec* source, const std::string &hostmask)
5028         {
5029                 OnLine(source,hostmask,false,'E',0,"");
5030         }
5031
5032         virtual void OnMode(userrec* user, void* dest, int target_type, const std::string &text)
5033         {
5034                 if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
5035                 {
5036                         if (target_type == TYPE_USER)
5037                         {
5038                                 userrec* u = (userrec*)dest;
5039                                 std::deque<std::string> params;
5040                                 params.push_back(u->nick);
5041                                 params.push_back(text);
5042                                 Utils->DoOneToMany(user->nick,"MODE",params);
5043                         }
5044                         else
5045                         {
5046                                 chanrec* c = (chanrec*)dest;
5047                                 std::deque<std::string> params;
5048                                 params.push_back(c->name);
5049                                 params.push_back(text);
5050                                 Utils->DoOneToMany(user->nick,"MODE",params);
5051                         }
5052                 }
5053         }
5054
5055         virtual void OnSetAway(userrec* user)
5056         {
5057                 if (IS_LOCAL(user))
5058                 {
5059                         std::deque<std::string> params;
5060                         params.push_back(":"+std::string(user->awaymsg));
5061                         Utils->DoOneToMany(user->nick,"AWAY",params);
5062                 }
5063         }
5064
5065         virtual void OnCancelAway(userrec* user)
5066         {
5067                 if (IS_LOCAL(user))
5068                 {
5069                         std::deque<std::string> params;
5070                         params.clear();
5071                         Utils->DoOneToMany(user->nick,"AWAY",params);
5072                 }
5073         }
5074
5075         virtual void ProtoSendMode(void* opaque, int target_type, void* target, const std::string &modeline)
5076         {
5077                 TreeSocket* s = (TreeSocket*)opaque;
5078                 if (target)
5079                 {
5080                         if (target_type == TYPE_USER)
5081                         {
5082                                 userrec* u = (userrec*)target;
5083                                 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+u->nick+" "+ConvToStr(u->age)+" "+modeline);
5084                         }
5085                         else
5086                         {
5087                                 chanrec* c = (chanrec*)target;
5088                                 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" FMODE "+c->name+" "+ConvToStr(c->age)+" "+modeline);
5089                         }
5090                 }
5091         }
5092
5093         virtual void ProtoSendMetaData(void* opaque, int target_type, void* target, const std::string &extname, const std::string &extdata)
5094         {
5095                 TreeSocket* s = (TreeSocket*)opaque;
5096                 if (target)
5097                 {
5098                         if (target_type == TYPE_USER)
5099                         {
5100                                 userrec* u = (userrec*)target;
5101                                 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+u->nick+" "+extname+" :"+extdata);
5102                         }
5103                         else if (target_type == TYPE_OTHER)
5104                         {
5105                                 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA * "+extname+" :"+extdata);
5106                         }
5107                         else if (target_type == TYPE_CHANNEL)
5108                         {
5109                                 chanrec* c = (chanrec*)target;
5110                                 s->WriteLine(std::string(":")+ServerInstance->Config->ServerName+" METADATA "+c->name+" "+extname+" :"+extdata);
5111                         }
5112                 }
5113         }
5114
5115         virtual void OnEvent(Event* event)
5116         {
5117                 std::deque<std::string>* params = (std::deque<std::string>*)event->GetData();
5118
5119                 if (event->GetEventID() == "send_metadata")
5120                 {
5121                         if (params->size() < 3)
5122                                 return;
5123                         (*params)[2] = ":" + (*params)[2];
5124                         Utils->DoOneToMany(ServerInstance->Config->ServerName,"METADATA",*params);
5125                 }
5126                 else if (event->GetEventID() == "send_topic")
5127                 {
5128                         if (params->size() < 2)
5129                                 return;
5130                         (*params)[1] = ":" + (*params)[1];
5131                         params->insert(params->begin() + 1,ServerInstance->Config->ServerName);
5132                         params->insert(params->begin() + 1,ConvToStr(ServerInstance->Time(true)));
5133                         Utils->DoOneToMany(ServerInstance->Config->ServerName,"FTOPIC",*params);
5134                 }
5135                 else if (event->GetEventID() == "send_mode")
5136                 {
5137                         if (params->size() < 2)
5138                                 return;
5139                         // Insert the TS value of the object, either userrec or chanrec
5140                         time_t ourTS = 0;
5141                         userrec* a = ServerInstance->FindNick((*params)[0]);
5142                         if (a)
5143                         {
5144                                 ourTS = a->age;
5145                         }
5146                         else
5147                         {
5148                                 chanrec* a = ServerInstance->FindChan((*params)[0]);
5149                                 if (a)
5150                                 {
5151                                         ourTS = a->age;
5152                                 }
5153                         }
5154                         params->insert(params->begin() + 1,ConvToStr(ourTS));
5155                         Utils->DoOneToMany(ServerInstance->Config->ServerName,"FMODE",*params);
5156                 }
5157                 else if (event->GetEventID() == "send_mode_explicit")
5158                 {
5159                         if (params->size() < 2)
5160                                 return;
5161                         // Insert the TS value of the object, either userrec or chanrec
5162                         Utils->DoOneToMany(ServerInstance->Config->ServerName,"MODE",*params);
5163                 }
5164                 else if (event->GetEventID() == "send_push")
5165                 {
5166                         if (params->size() < 2)
5167                                 return;
5168                         
5169                         userrec *a = ServerInstance->FindNick((*params)[0]);
5170                         
5171                         if (!a)
5172                                 return;
5173                         
5174                         (*params)[1] = ":" + (*params)[1];
5175                         Utils->DoOneToOne(ServerInstance->Config->ServerName, "PUSH", *params, a->server);
5176                 }
5177         }
5178
5179         virtual ~ModuleSpanningTree()
5180         {
5181                 ServerInstance->Log(DEBUG,"Performing unload of spanningtree!");
5182                 /* This will also free the listeners */
5183                 delete Utils;
5184                 if (SyncTimer)
5185                         ServerInstance->Timers->DelTimer(SyncTimer);
5186         }
5187
5188         virtual Version GetVersion()
5189         {
5190                 return Version(1,1,0,2,VF_VENDOR,API_VERSION);
5191         }
5192
5193         void Implements(char* List)
5194         {
5195                 List[I_OnPreCommand] = List[I_OnGetServerDescription] = List[I_OnUserInvite] = List[I_OnPostLocalTopicChange] = 1;
5196                 List[I_OnWallops] = List[I_OnUserNotice] = List[I_OnUserMessage] = List[I_OnBackgroundTimer] = 1;
5197                 List[I_OnUserJoin] = List[I_OnChangeHost] = List[I_OnChangeName] = List[I_OnUserPart] = List[I_OnUserConnect] = 1;
5198                 List[I_OnUserQuit] = List[I_OnUserPostNick] = List[I_OnUserKick] = List[I_OnRemoteKill] = List[I_OnRehash] = 1;
5199                 List[I_OnOper] = List[I_OnAddGLine] = List[I_OnAddZLine] = List[I_OnAddQLine] = List[I_OnAddELine] = 1;
5200                 List[I_OnDelGLine] = List[I_OnDelZLine] = List[I_OnDelQLine] = List[I_OnDelELine] = List[I_ProtoSendMode] = List[I_OnMode] = 1;
5201                 List[I_OnStats] = List[I_ProtoSendMetaData] = List[I_OnEvent] = List[I_OnSetAway] = List[I_OnCancelAway] = List[I_OnPostCommand] = 1;
5202         }
5203
5204         /* It is IMPORTANT that m_spanningtree is the last module in the chain
5205          * so that any activity it sees is FINAL, e.g. we arent going to send out
5206          * a NICK message before m_cloaking has finished putting the +x on the user,
5207          * etc etc.
5208          * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
5209          * the module call queue.
5210          */
5211         Priority Prioritize()
5212         {
5213                 return PRIORITY_LAST;
5214         }
5215 };
5216
5217 TimeSyncTimer::TimeSyncTimer(InspIRCd *Inst, ModuleSpanningTree *Mod) : InspTimer(43200, Inst->Time()), Instance(Inst), Module(Mod)
5218 {
5219 }
5220
5221 void TimeSyncTimer::Tick(time_t TIME)
5222 {
5223         Module->BroadcastTimeSync();
5224         Module->SyncTimer = new TimeSyncTimer(Instance, Module);
5225         Instance->Timers->AddTimer(Module->SyncTimer);
5226 }
5227
5228 void SpanningTreeUtilities::DoFailOver(Link* x)
5229 {
5230         if (x->FailOver.length())
5231         {
5232                 if (x->FailOver == x->Name)
5233                 {
5234                         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());
5235                         return;
5236                 }
5237                 Link* TryThisOne = this->FindLink(x->FailOver.c_str());
5238                 if (TryThisOne)
5239                 {
5240                         ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Trying failover link for \002%s\002: \002%s\002...", x->Name.c_str(), TryThisOne->Name.c_str());
5241                         Creator->ConnectServer(TryThisOne);
5242                 }
5243                 else
5244                 {
5245                         ServerInstance->SNO->WriteToSnoMask('l',"FAILOVER: Invalid failover server specified for server \002%s\002, will not follow!", x->Name.c_str());
5246                 }
5247         }
5248 }
5249
5250 Link* SpanningTreeUtilities::FindLink(const std::string& name)
5251 {
5252         for (std::vector<Link>::iterator x = LinkBlocks.begin(); x < LinkBlocks.end(); x++)
5253         {
5254                 if (ServerInstance->MatchText(x->Name.c_str(), name.c_str()))
5255                 {
5256                         return &(*x);
5257                 }
5258         }
5259         return NULL;
5260 }
5261
5262 class ModuleSpanningTreeFactory : public ModuleFactory
5263 {
5264  public:
5265         ModuleSpanningTreeFactory()
5266         {
5267         }
5268         
5269         ~ModuleSpanningTreeFactory()
5270         {
5271         }
5272         
5273         virtual Module * CreateModule(InspIRCd* Me)
5274         {
5275                 return new ModuleSpanningTree(Me);
5276         }
5277         
5278 };
5279
5280
5281 extern "C" void * init_module( void )
5282 {
5283         return new ModuleSpanningTreeFactory;
5284 }