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