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