]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/main.cpp
m_spanningtree Replace #defines with references in DoCollision()
[user/henk/code/inspircd.git] / src / modules / m_spanningtree / main.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5  *   Copyright (C) 2007-2009 Craig Edwards <craigedwards@brainbox.cc>
6  *   Copyright (C) 2007-2008 Robin Burchell <robin+git@viroteck.net>
7  *   Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
8  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
9  *
10  * This file is part of InspIRCd.  InspIRCd is free software: you can
11  * redistribute it and/or modify it under the terms of the GNU General Public
12  * License as published by the Free Software Foundation, version 2.
13  *
14  * This program is distributed in the hope that it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
17  * details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  */
22
23
24 #include "inspircd.h"
25 #include "socket.h"
26 #include "xline.h"
27 #include "iohook.h"
28
29 #include "resolvers.h"
30 #include "main.h"
31 #include "utils.h"
32 #include "treeserver.h"
33 #include "link.h"
34 #include "treesocket.h"
35 #include "commands.h"
36
37 ModuleSpanningTree::ModuleSpanningTree()
38         : rconnect(this), rsquit(this), map(this)
39         , commands(NULL)
40         , currmembid(0)
41         , DNS(this, "DNS")
42         , loopCall(false)
43         , SplitInProgress(false)
44 {
45 }
46
47 SpanningTreeCommands::SpanningTreeCommands(ModuleSpanningTree* module)
48         : svsjoin(module), svspart(module), svsnick(module), metadata(module),
49         uid(module), opertype(module), fjoin(module), ijoin(module), resync(module),
50         fmode(module), ftopic(module), fhost(module), fident(module), fname(module),
51         away(module), addline(module), delline(module), encap(module), idle(module),
52         nick(module), ping(module), pong(module), push(module), save(module),
53         server(module), squit(module), snonotice(module),
54         burst(module), endburst(module), sinfo(module)
55 {
56 }
57
58 namespace
59 {
60         void SetLocalUsersServer(Server* newserver)
61         {
62                 // Does not change the server of quitting users because those are not in the list
63
64                 ServerInstance->FakeClient->server = newserver;
65                 const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
66                 for (UserManager::LocalList::const_iterator i = list.begin(); i != list.end(); ++i)
67                         (*i)->server = newserver;
68         }
69
70         void ResetMembershipIds()
71         {
72                 // Set all membership ids to 0
73                 const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
74                 for (UserManager::LocalList::iterator i = list.begin(); i != list.end(); ++i)
75                 {
76                         LocalUser* user = *i;
77                         for (User::ChanList::iterator j = user->chans.begin(); j != user->chans.end(); ++j)
78                                 (*j)->id = 0;
79                 }
80         }
81 }
82
83 void ModuleSpanningTree::init()
84 {
85         ServerInstance->SNO->EnableSnomask('l', "LINK");
86
87         ResetMembershipIds();
88
89         Utils = new SpanningTreeUtilities(this);
90         Utils->TreeRoot = new TreeServer;
91         commands = new SpanningTreeCommands(this);
92
93         ServerInstance->PI = &protocolinterface;
94
95         delete ServerInstance->FakeClient->server;
96         SetLocalUsersServer(Utils->TreeRoot);
97 }
98
99 void ModuleSpanningTree::ShowLinks(TreeServer* Current, User* user, int hops)
100 {
101         std::string Parent = Utils->TreeRoot->GetName();
102         if (Current->GetParent())
103         {
104                 Parent = Current->GetParent()->GetName();
105         }
106
107         const TreeServer::ChildServers& children = Current->GetChildren();
108         for (TreeServer::ChildServers::const_iterator i = children.begin(); i != children.end(); ++i)
109         {
110                 TreeServer* server = *i;
111                 if ((server->Hidden) || ((Utils->HideULines) && (server->IsULine())))
112                 {
113                         if (user->IsOper())
114                         {
115                                  ShowLinks(server, user, hops+1);
116                         }
117                 }
118                 else
119                 {
120                         ShowLinks(server, user, hops+1);
121                 }
122         }
123         /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
124         if ((Utils->HideULines) && (Current->IsULine()) && (!user->IsOper()))
125                 return;
126         /* Or if the server is hidden and they're not an oper */
127         else if ((Current->Hidden) && (!user->IsOper()))
128                 return;
129
130         user->WriteNumeric(RPL_LINKS, "%s %s :%d %s",   Current->GetName().c_str(),
131                         (Utils->FlatLinks && (!user->IsOper())) ? ServerInstance->Config->ServerName.c_str() : Parent.c_str(),
132                         (Utils->FlatLinks && (!user->IsOper())) ? 0 : hops,
133                         Current->GetDesc().c_str());
134 }
135
136 void ModuleSpanningTree::HandleLinks(const std::vector<std::string>& parameters, User* user)
137 {
138         ShowLinks(Utils->TreeRoot,user,0);
139         user->WriteNumeric(RPL_ENDOFLINKS, "* :End of /LINKS list.");
140 }
141
142 std::string ModuleSpanningTree::TimeToStr(time_t secs)
143 {
144         time_t mins_up = secs / 60;
145         time_t hours_up = mins_up / 60;
146         time_t days_up = hours_up / 24;
147         secs = secs % 60;
148         mins_up = mins_up % 60;
149         hours_up = hours_up % 24;
150         return ((days_up ? (ConvToStr(days_up) + "d") : "")
151                         + (hours_up ? (ConvToStr(hours_up) + "h") : "")
152                         + (mins_up ? (ConvToStr(mins_up) + "m") : "")
153                         + ConvToStr(secs) + "s");
154 }
155
156 void ModuleSpanningTree::DoPingChecks(time_t curtime)
157 {
158         /*
159          * Cancel remote burst mode on any servers which still have it enabled due to latency/lack of data.
160          * This prevents lost REMOTECONNECT notices
161          */
162         long ts = ServerInstance->Time() * 1000 + (ServerInstance->Time_ns() / 1000000);
163
164 restart:
165         for (server_hash::iterator i = Utils->serverlist.begin(); i != Utils->serverlist.end(); i++)
166         {
167                 TreeServer *s = i->second;
168
169                 // Skip myself
170                 if (s->IsRoot())
171                         continue;
172
173                 if (s->GetSocket()->GetLinkState() == DYING)
174                 {
175                         s->GetSocket()->Close();
176                         goto restart;
177                 }
178
179                 // Do not ping servers that are not fully connected yet!
180                 // Servers which are connected to us have IsLocal() == true and if they're fully connected
181                 // then Socket->LinkState == CONNECTED. Servers that are linked to another server are always fully connected.
182                 if (s->IsLocal() && s->GetSocket()->GetLinkState() != CONNECTED)
183                         continue;
184
185                 // Now do PING checks on all servers
186                 // Only ping if this server needs one
187                 if (curtime >= s->NextPingTime())
188                 {
189                         // And if they answered the last
190                         if (s->AnsweredLastPing())
191                         {
192                                 // They did, send a ping to them
193                                 s->SetNextPingTime(curtime + Utils->PingFreq);
194                                 s->GetSocket()->WriteLine(CmdBuilder("PING").push(s->GetID()));
195                                 s->LastPingMsec = ts;
196                         }
197                         else
198                         {
199                                 // They didn't answer the last ping, if they are locally connected, get rid of them.
200                                 if (s->IsLocal())
201                                 {
202                                         TreeSocket* sock = s->GetSocket();
203                                         sock->SendError("Ping timeout");
204                                         sock->Close();
205                                         goto restart;
206                                 }
207                         }
208                 }
209
210                 // If warn on ping enabled and not warned and the difference is sufficient and they didn't answer the last ping...
211                 if ((Utils->PingWarnTime) && (!s->Warned) && (curtime >= s->NextPingTime() - (Utils->PingFreq - Utils->PingWarnTime)) && (!s->AnsweredLastPing()))
212                 {
213                         /* The server hasnt responded, send a warning to opers */
214                         ServerInstance->SNO->WriteToSnoMask('l',"Server \002%s\002 has not responded to PING for %d seconds, high latency.", s->GetName().c_str(), Utils->PingWarnTime);
215                         s->Warned = true;
216                 }
217         }
218 }
219
220 void ModuleSpanningTree::ConnectServer(Autoconnect* a, bool on_timer)
221 {
222         if (!a)
223                 return;
224         for(unsigned int j=0; j < a->servers.size(); j++)
225         {
226                 if (Utils->FindServer(a->servers[j]))
227                 {
228                         // found something in this block. Should the server fail,
229                         // we want to start at the start of the list, not in the
230                         // middle where we left off
231                         a->position = -1;
232                         return;
233                 }
234         }
235         if (on_timer && a->position >= 0)
236                 return;
237         if (!on_timer && a->position < 0)
238                 return;
239
240         a->position++;
241         while (a->position < (int)a->servers.size())
242         {
243                 Link* x = Utils->FindLink(a->servers[a->position]);
244                 if (x)
245                 {
246                         ServerInstance->SNO->WriteToSnoMask('l', "AUTOCONNECT: Auto-connecting server \002%s\002", x->Name.c_str());
247                         ConnectServer(x, a);
248                         return;
249                 }
250                 a->position++;
251         }
252         // Autoconnect chain has been fully iterated; start at the beginning on the
253         // next AutoConnectServers run
254         a->position = -1;
255 }
256
257 void ModuleSpanningTree::ConnectServer(Link* x, Autoconnect* y)
258 {
259         bool ipvalid = true;
260
261         if (InspIRCd::Match(ServerInstance->Config->ServerName, assign(x->Name), rfc_case_insensitive_map))
262         {
263                 ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Not connecting to myself.");
264                 return;
265         }
266
267         DNS::QueryType start_type = DNS::QUERY_AAAA;
268         if (strchr(x->IPAddr.c_str(),':'))
269         {
270                 in6_addr n;
271                 if (inet_pton(AF_INET6, x->IPAddr.c_str(), &n) < 1)
272                         ipvalid = false;
273         }
274         else
275         {
276                 in_addr n;
277                 if (inet_aton(x->IPAddr.c_str(),&n) < 1)
278                         ipvalid = false;
279         }
280
281         /* Do we already have an IP? If so, no need to resolve it. */
282         if (ipvalid)
283         {
284                 /* Gave a hook, but it wasnt one we know */
285                 TreeSocket* newsocket = new TreeSocket(x, y, x->IPAddr);
286                 if (newsocket->GetFd() > -1)
287                 {
288                         /* Handled automatically on success */
289                 }
290                 else
291                 {
292                         ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: %s.",
293                                 x->Name.c_str(), newsocket->getError().c_str());
294                         ServerInstance->GlobalCulls.AddItem(newsocket);
295                 }
296         }
297         else if (!DNS)
298         {
299                 ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: Hostname given and m_dns.so is not loaded, unable to resolve.", x->Name.c_str());
300         }
301         else
302         {
303                 ServernameResolver* snr = new ServernameResolver(*DNS, x->IPAddr, x, start_type, y);
304                 try
305                 {
306                         DNS->Process(snr);
307                 }
308                 catch (DNS::Exception& e)
309                 {
310                         delete snr;
311                         ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(), e.GetReason().c_str());
312                         ConnectServer(y, false);
313                 }
314         }
315 }
316
317 void ModuleSpanningTree::AutoConnectServers(time_t curtime)
318 {
319         for (std::vector<reference<Autoconnect> >::iterator i = Utils->AutoconnectBlocks.begin(); i < Utils->AutoconnectBlocks.end(); ++i)
320         {
321                 Autoconnect* x = *i;
322                 if (curtime >= x->NextConnectTime)
323                 {
324                         x->NextConnectTime = curtime + x->Period;
325                         ConnectServer(x, true);
326                 }
327         }
328 }
329
330 void ModuleSpanningTree::DoConnectTimeout(time_t curtime)
331 {
332         std::map<TreeSocket*, std::pair<std::string, int> >::iterator i = Utils->timeoutlist.begin();
333         while (i != Utils->timeoutlist.end())
334         {
335                 TreeSocket* s = i->first;
336                 std::pair<std::string, int> p = i->second;
337                 std::map<TreeSocket*, std::pair<std::string, int> >::iterator me = i;
338                 i++;
339                 if (s->GetLinkState() == DYING)
340                 {
341                         Utils->timeoutlist.erase(me);
342                         s->Close();
343                 }
344                 else if (curtime > s->age + p.second)
345                 {
346                         ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002 (timeout of %d seconds)",p.first.c_str(),p.second);
347                         Utils->timeoutlist.erase(me);
348                         s->Close();
349                 }
350         }
351 }
352
353 ModResult ModuleSpanningTree::HandleVersion(const std::vector<std::string>& parameters, User* user)
354 {
355         // we've already checked if pcnt > 0, so this is safe
356         TreeServer* found = Utils->FindServerMask(parameters[0]);
357         if (found)
358         {
359                 if (found == Utils->TreeRoot)
360                 {
361                         // Pass to default VERSION handler.
362                         return MOD_RES_PASSTHRU;
363                 }
364
365                 // If an oper wants to see the version then show the full version string instead of the normal,
366                 // but only if it is non-empty.
367                 // If it's empty it might be that the server is still syncing (full version hasn't arrived yet)
368                 // or the server is a 2.0 server and does not send a full version.
369                 bool showfull = ((user->IsOper()) && (!found->GetFullVersion().empty()));
370                 const std::string& Version = (showfull ? found->GetFullVersion() : found->GetVersion());
371                 user->WriteNumeric(RPL_VERSION, ":%s", Version.c_str());
372         }
373         else
374         {
375                 user->WriteNumeric(ERR_NOSUCHSERVER, "%s :No such server", parameters[0].c_str());
376         }
377         return MOD_RES_DENY;
378 }
379
380 /* This method will attempt to get a message to a remote user.
381  */
382 void ModuleSpanningTree::RemoteMessage(User* user, const char* format, ...)
383 {
384         std::string text;
385         VAFORMAT(text, format, format);
386
387         if (IS_LOCAL(user))
388                 user->WriteNotice(text);
389         else
390                 ServerInstance->PI->SendUserNotice(user, text);
391 }
392
393 ModResult ModuleSpanningTree::HandleConnect(const std::vector<std::string>& parameters, User* user)
394 {
395         for (std::vector<reference<Link> >::iterator i = Utils->LinkBlocks.begin(); i < Utils->LinkBlocks.end(); i++)
396         {
397                 Link* x = *i;
398                 if (InspIRCd::Match(x->Name.c_str(),parameters[0], rfc_case_insensitive_map))
399                 {
400                         if (InspIRCd::Match(ServerInstance->Config->ServerName, assign(x->Name), rfc_case_insensitive_map))
401                         {
402                                 RemoteMessage(user, "*** CONNECT: Server \002%s\002 is ME, not connecting.",x->Name.c_str());
403                                 return MOD_RES_DENY;
404                         }
405
406                         TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
407                         if (!CheckDupe)
408                         {
409                                 RemoteMessage(user, "*** CONNECT: Connecting to server: \002%s\002 (%s:%d)",x->Name.c_str(),(x->HiddenFromStats ? "<hidden>" : x->IPAddr.c_str()),x->Port);
410                                 ConnectServer(x);
411                                 return MOD_RES_DENY;
412                         }
413                         else
414                         {
415                                 RemoteMessage(user, "*** CONNECT: Server \002%s\002 already exists on the network and is connected via \002%s\002", x->Name.c_str(), CheckDupe->GetParent()->GetName().c_str());
416                                 return MOD_RES_DENY;
417                         }
418                 }
419         }
420         RemoteMessage(user, "*** CONNECT: No server matching \002%s\002 could be found in the config file.",parameters[0].c_str());
421         return MOD_RES_DENY;
422 }
423
424 void ModuleSpanningTree::OnUserInvite(User* source,User* dest,Channel* channel, time_t expiry)
425 {
426         if (IS_LOCAL(source))
427         {
428                 CmdBuilder params(source, "INVITE");
429                 params.push_back(dest->uuid);
430                 params.push_back(channel->name);
431                 params.push_int(channel->age);
432                 params.push_back(ConvToStr(expiry));
433                 params.Broadcast();
434         }
435 }
436
437 void ModuleSpanningTree::OnPostTopicChange(User* user, Channel* chan, const std::string &topic)
438 {
439         // Drop remote events on the floor.
440         if (!IS_LOCAL(user))
441                 return;
442
443         CommandFTopic::Builder(user, chan).Broadcast();
444 }
445
446 void ModuleSpanningTree::OnUserMessage(User* user, void* dest, int target_type, const std::string& text, char status, const CUList& exempt_list, MessageType msgtype)
447 {
448         if (!IS_LOCAL(user))
449                 return;
450
451         const char* message_type = (msgtype == MSG_PRIVMSG ? "PRIVMSG" : "NOTICE");
452         if (target_type == TYPE_USER)
453         {
454                 User* d = (User*) dest;
455                 if (!IS_LOCAL(d))
456                 {
457                         CmdBuilder params(user, message_type);
458                         params.push_back(d->uuid);
459                         params.push_last(text);
460                         params.Unicast(d);
461                 }
462         }
463         else if (target_type == TYPE_CHANNEL)
464         {
465                 Utils->SendChannelMessage(user->uuid, (Channel*)dest, text, status, exempt_list, message_type);
466         }
467         else if (target_type == TYPE_SERVER)
468         {
469                 char* target = (char*) dest;
470                 CmdBuilder par(user, message_type);
471                 par.push_back(target);
472                 par.push_last(text);
473                 par.Broadcast();
474         }
475 }
476
477 void ModuleSpanningTree::OnBackgroundTimer(time_t curtime)
478 {
479         AutoConnectServers(curtime);
480         DoPingChecks(curtime);
481         DoConnectTimeout(curtime);
482 }
483
484 void ModuleSpanningTree::OnUserConnect(LocalUser* user)
485 {
486         if (user->quitting)
487                 return;
488
489         CommandUID::Builder(user).Broadcast();
490
491         if (user->IsOper())
492                 CommandOpertype::Builder(user).Broadcast();
493
494         for(Extensible::ExtensibleStore::const_iterator i = user->GetExtList().begin(); i != user->GetExtList().end(); i++)
495         {
496                 ExtensionItem* item = i->first;
497                 std::string value = item->serialize(FORMAT_NETWORK, user, i->second);
498                 if (!value.empty())
499                         ServerInstance->PI->SendMetaData(user, item->name, value);
500         }
501
502         Utils->TreeRoot->UserCount++;
503 }
504
505 void ModuleSpanningTree::OnUserJoin(Membership* memb, bool sync, bool created_by_local, CUList& excepts)
506 {
507         // Only do this for local users
508         if (!IS_LOCAL(memb->user))
509                 return;
510
511         // Assign the current membership id to the new Membership and increase it
512         memb->id = currmembid++;
513
514         if (created_by_local)
515         {
516                 CommandFJoin::Builder params(memb->chan);
517                 params.add(memb);
518                 params.finalize();
519                 params.Broadcast();
520         }
521         else
522         {
523                 CmdBuilder params(memb->user, "IJOIN");
524                 params.push_back(memb->chan->name);
525                 params.push_int(memb->id);
526                 if (!memb->modes.empty())
527                 {
528                         params.push_back(ConvToStr(memb->chan->age));
529                         params.push_back(memb->modes);
530                 }
531                 params.Broadcast();
532         }
533 }
534
535 void ModuleSpanningTree::OnChangeHost(User* user, const std::string &newhost)
536 {
537         if (user->registered != REG_ALL || !IS_LOCAL(user))
538                 return;
539
540         CmdBuilder(user, "FHOST").push(newhost).Broadcast();
541 }
542
543 void ModuleSpanningTree::OnChangeName(User* user, const std::string &gecos)
544 {
545         if (user->registered != REG_ALL || !IS_LOCAL(user))
546                 return;
547
548         CmdBuilder(user, "FNAME").push_last(gecos).Broadcast();
549 }
550
551 void ModuleSpanningTree::OnChangeIdent(User* user, const std::string &ident)
552 {
553         if ((user->registered != REG_ALL) || (!IS_LOCAL(user)))
554                 return;
555
556         CmdBuilder(user, "FIDENT").push(ident).Broadcast();
557 }
558
559 void ModuleSpanningTree::OnUserPart(Membership* memb, std::string &partmessage, CUList& excepts)
560 {
561         if (IS_LOCAL(memb->user))
562         {
563                 CmdBuilder params(memb->user, "PART");
564                 params.push_back(memb->chan->name);
565                 if (!partmessage.empty())
566                         params.push_last(partmessage);
567                 params.Broadcast();
568         }
569 }
570
571 void ModuleSpanningTree::OnUserQuit(User* user, const std::string &reason, const std::string &oper_message)
572 {
573         if (IS_LOCAL(user))
574         {
575                 if (oper_message != reason)
576                         ServerInstance->PI->SendMetaData(user, "operquit", oper_message);
577
578                 CmdBuilder(user, "QUIT").push_last(reason).Broadcast();
579         }
580         else
581         {
582                 // Hide the message if one of the following is true:
583                 // - User is being quit due to a netsplit and quietbursts is on
584                 // - Server is a silent uline
585                 bool hide = (((this->SplitInProgress) && (Utils->quiet_bursts)) || (user->server->IsSilentULine()));
586                 if (!hide)
587                 {
588                         ServerInstance->SNO->WriteToSnoMask('Q', "Client exiting on server %s: %s (%s) [%s]",
589                                 user->server->GetName().c_str(), user->GetFullRealHost().c_str(), user->GetIPString().c_str(), oper_message.c_str());
590                 }
591         }
592
593         // Regardless, We need to modify the user Counts..
594         TreeServer::Get(user)->UserCount--;
595 }
596
597 void ModuleSpanningTree::OnUserPostNick(User* user, const std::string &oldnick)
598 {
599         if (IS_LOCAL(user))
600         {
601                 // The nick TS is updated by the core, we don't do it
602                 CmdBuilder params(user, "NICK");
603                 params.push_back(user->nick);
604                 params.push_back(ConvToStr(user->age));
605                 params.Broadcast();
606         }
607         else if (!loopCall && user->nick == user->uuid)
608         {
609                 CmdBuilder params("SAVE");
610                 params.push_back(user->uuid);
611                 params.push_back(ConvToStr(user->age));
612                 params.Broadcast();
613         }
614 }
615
616 void ModuleSpanningTree::OnUserKick(User* source, Membership* memb, const std::string &reason, CUList& excepts)
617 {
618         if ((!IS_LOCAL(source)) && (source != ServerInstance->FakeClient))
619                 return;
620
621         CmdBuilder params(source, "KICK");
622         params.push_back(memb->chan->name);
623         params.push_back(memb->user->uuid);
624         // If a remote user is being kicked by us then send the membership id in the kick too
625         if (!IS_LOCAL(memb->user))
626                 params.push_int(memb->id);
627         params.push_last(reason);
628         params.Broadcast();
629 }
630
631 void ModuleSpanningTree::OnPreRehash(User* user, const std::string &parameter)
632 {
633         if (loopCall)
634                 return; // Don't generate a REHASH here if we're in the middle of processing a message that generated this one
635
636         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "OnPreRehash called with param %s", parameter.c_str());
637
638         // Send out to other servers
639         if (!parameter.empty() && parameter[0] != '-')
640         {
641                 CmdBuilder params((user ? user->uuid : ServerInstance->Config->GetSID()), "REHASH");
642                 params.push_back(parameter);
643                 params.Forward(user ? TreeServer::Get(user)->GetRoute() : NULL);
644         }
645 }
646
647 void ModuleSpanningTree::ReadConfig(ConfigStatus& status)
648 {
649         // Did this rehash change the description of this server?
650         const std::string& newdesc = ServerInstance->Config->ServerDesc;
651         if (newdesc != Utils->TreeRoot->GetDesc())
652         {
653                 // Broadcast a SINFO desc message to let the network know about the new description. This is the description
654                 // string that is sent in the SERVER message initially and shown for example in WHOIS.
655                 // We don't need to update the field itself in the Server object - the core does that.
656                 CommandSInfo::Builder(Utils->TreeRoot, "desc", newdesc).Broadcast();
657         }
658
659         // Re-read config stuff
660         try
661         {
662                 Utils->ReadConfiguration();
663         }
664         catch (ModuleException& e)
665         {
666                 // Refresh the IP cache anyway, so servers read before the error will be allowed to connect
667                 Utils->RefreshIPCache();
668                 // Always warn local opers with snomask +l, also warn globally (snomask +L) if the rehash was issued by a remote user
669                 std::string msg = "Error in configuration: ";
670                 msg.append(e.GetReason());
671                 ServerInstance->SNO->WriteToSnoMask('l', msg);
672                 if (status.srcuser && !IS_LOCAL(status.srcuser))
673                         ServerInstance->PI->SendSNONotice('L', msg);
674         }
675 }
676
677 void ModuleSpanningTree::OnLoadModule(Module* mod)
678 {
679         std::string data;
680         data.push_back('+');
681         data.append(mod->ModuleSourceFile);
682         Version v = mod->GetVersion();
683         if (!v.link_data.empty())
684         {
685                 data.push_back('=');
686                 data.append(v.link_data);
687         }
688         ServerInstance->PI->SendMetaData("modules", data);
689 }
690
691 void ModuleSpanningTree::OnUnloadModule(Module* mod)
692 {
693         if (!Utils)
694                 return;
695         ServerInstance->PI->SendMetaData("modules", "-" + mod->ModuleSourceFile);
696
697 restart:
698         // Close all connections which use an IO hook provided by this module
699         const TreeServer::ChildServers& list = Utils->TreeRoot->GetChildren();
700         for (TreeServer::ChildServers::const_iterator i = list.begin(); i != list.end(); ++i)
701         {
702                 TreeSocket* sock = (*i)->GetSocket();
703                 if (sock->GetIOHook() && sock->GetIOHook()->prov->creator == mod)
704                 {
705                         sock->SendError("SSL module unloaded");
706                         sock->Close();
707                         // XXX: The list we're iterating is modified by TreeSocket::Squit() which is called by Close()
708                         goto restart;
709                 }
710         }
711
712         for (SpanningTreeUtilities::TimeoutList::const_iterator i = Utils->timeoutlist.begin(); i != Utils->timeoutlist.end(); ++i)
713         {
714                 TreeSocket* sock = i->first;
715                 if (sock->GetIOHook() && sock->GetIOHook()->prov->creator == mod)
716                         sock->Close();
717         }
718 }
719
720 // note: the protocol does not allow direct umode +o except
721 // via NICK with 8 params. sending OPERTYPE infers +o modechange
722 // locally.
723 void ModuleSpanningTree::OnOper(User* user, const std::string &opertype)
724 {
725         if (user->registered != REG_ALL || !IS_LOCAL(user))
726                 return;
727         CommandOpertype::Builder(user).Broadcast();
728 }
729
730 void ModuleSpanningTree::OnAddLine(User* user, XLine *x)
731 {
732         if (!x->IsBurstable() || loopCall || (user && !IS_LOCAL(user)))
733                 return;
734
735         if (!user)
736                 user = ServerInstance->FakeClient;
737
738         CommandAddLine::Builder(x, user).Broadcast();
739 }
740
741 void ModuleSpanningTree::OnDelLine(User* user, XLine *x)
742 {
743         if (!x->IsBurstable() || loopCall || (user && !IS_LOCAL(user)))
744                 return;
745
746         if (!user)
747                 user = ServerInstance->FakeClient;
748
749         CmdBuilder params(user, "DELLINE");
750         params.push_back(x->type);
751         params.push_back(x->Displayable());
752         params.Broadcast();
753 }
754
755 ModResult ModuleSpanningTree::OnSetAway(User* user, const std::string &awaymsg)
756 {
757         if (IS_LOCAL(user))
758                 CommandAway::Builder(user, awaymsg).Broadcast();
759
760         return MOD_RES_PASSTHRU;
761 }
762
763 CullResult ModuleSpanningTree::cull()
764 {
765         if (Utils)
766                 Utils->cull();
767         return this->Module::cull();
768 }
769
770 ModuleSpanningTree::~ModuleSpanningTree()
771 {
772         ServerInstance->PI = &ServerInstance->DefaultProtocolInterface;
773
774         Server* newsrv = new Server(ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc);
775         SetLocalUsersServer(newsrv);
776
777         /* This will also free the listeners */
778         delete Utils;
779
780         delete commands;
781 }
782
783 Version ModuleSpanningTree::GetVersion()
784 {
785         return Version("Allows servers to be linked", VF_VENDOR);
786 }
787
788 /* It is IMPORTANT that m_spanningtree is the last module in the chain
789  * so that any activity it sees is FINAL, e.g. we arent going to send out
790  * a NICK message before m_cloaking has finished putting the +x on the user,
791  * etc etc.
792  * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
793  * the module call queue.
794  */
795 void ModuleSpanningTree::Prioritize()
796 {
797         ServerInstance->Modules->SetPriority(this, PRIORITY_LAST);
798 }
799
800 MODULE_INIT(ModuleSpanningTree)