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