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