]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/main.cpp
3393539cc735d9d7059e8d2ef34b8cfd9bf2d790
[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                 ServerInstance->FakeClient->server = newserver;
63                 const LocalUserList& list = ServerInstance->Users->local_users;
64                 for (LocalUserList::const_iterator i = list.begin(); i != list.end(); ++i)
65                         (*i)->server = newserver;
66         }
67
68         void ResetMembershipIds()
69         {
70                 // Set all membership ids to 0
71                 const LocalUserList& list = ServerInstance->Users->local_users;
72                 for (LocalUserList::iterator i = list.begin(); i != list.end(); ++i)
73                 {
74                         LocalUser* user = *i;
75                         for (User::ChanList::iterator j = user->chans.begin(); j != user->chans.end(); ++j)
76                                 (*j)->id = 0;
77                 }
78         }
79 }
80
81 void ModuleSpanningTree::init()
82 {
83         ServerInstance->SNO->EnableSnomask('l', "LINK");
84
85         ResetMembershipIds();
86
87         Utils = new SpanningTreeUtilities(this);
88         Utils->TreeRoot = new TreeServer;
89         commands = new SpanningTreeCommands(this);
90
91         ServerInstance->PI = &protocolinterface;
92
93         delete ServerInstance->FakeClient->server;
94         SetLocalUsersServer(Utils->TreeRoot);
95 }
96
97 void ModuleSpanningTree::ShowLinks(TreeServer* Current, User* user, int hops)
98 {
99         std::string Parent = Utils->TreeRoot->GetName();
100         if (Current->GetParent())
101         {
102                 Parent = Current->GetParent()->GetName();
103         }
104
105         const TreeServer::ChildServers& children = Current->GetChildren();
106         for (TreeServer::ChildServers::const_iterator i = children.begin(); i != children.end(); ++i)
107         {
108                 TreeServer* server = *i;
109                 if ((server->Hidden) || ((Utils->HideULines) && (server->IsULine())))
110                 {
111                         if (user->IsOper())
112                         {
113                                  ShowLinks(server, user, hops+1);
114                         }
115                 }
116                 else
117                 {
118                         ShowLinks(server, user, hops+1);
119                 }
120         }
121         /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
122         if ((Utils->HideULines) && (Current->IsULine()) && (!user->IsOper()))
123                 return;
124         /* Or if the server is hidden and they're not an oper */
125         else if ((Current->Hidden) && (!user->IsOper()))
126                 return;
127
128         user->WriteNumeric(RPL_LINKS, "%s %s :%d %s",   Current->GetName().c_str(),
129                         (Utils->FlatLinks && (!user->IsOper())) ? ServerInstance->Config->ServerName.c_str() : Parent.c_str(),
130                         (Utils->FlatLinks && (!user->IsOper())) ? 0 : hops,
131                         Current->GetDesc().c_str());
132 }
133
134 void ModuleSpanningTree::HandleLinks(const std::vector<std::string>& parameters, User* user)
135 {
136         ShowLinks(Utils->TreeRoot,user,0);
137         user->WriteNumeric(RPL_ENDOFLINKS, "* :End of /LINKS list.");
138 }
139
140 std::string ModuleSpanningTree::TimeToStr(time_t secs)
141 {
142         time_t mins_up = secs / 60;
143         time_t hours_up = mins_up / 60;
144         time_t days_up = hours_up / 24;
145         secs = secs % 60;
146         mins_up = mins_up % 60;
147         hours_up = hours_up % 24;
148         return ((days_up ? (ConvToStr(days_up) + "d") : "")
149                         + (hours_up ? (ConvToStr(hours_up) + "h") : "")
150                         + (mins_up ? (ConvToStr(mins_up) + "m") : "")
151                         + ConvToStr(secs) + "s");
152 }
153
154 void ModuleSpanningTree::DoPingChecks(time_t curtime)
155 {
156         /*
157          * Cancel remote burst mode on any servers which still have it enabled due to latency/lack of data.
158          * This prevents lost REMOTECONNECT notices
159          */
160         long ts = ServerInstance->Time() * 1000 + (ServerInstance->Time_ns() / 1000000);
161
162 restart:
163         for (server_hash::iterator i = Utils->serverlist.begin(); i != Utils->serverlist.end(); i++)
164         {
165                 TreeServer *s = i->second;
166
167                 // Skip myself
168                 if (s->IsRoot())
169                         continue;
170
171                 if (s->GetSocket()->GetLinkState() == DYING)
172                 {
173                         s->GetSocket()->Close();
174                         goto restart;
175                 }
176
177                 // Do not ping servers that are not fully connected yet!
178                 // Servers which are connected to us have IsLocal() == true and if they're fully connected
179                 // then Socket->LinkState == CONNECTED. Servers that are linked to another server are always fully connected.
180                 if (s->IsLocal() && s->GetSocket()->GetLinkState() != CONNECTED)
181                         continue;
182
183                 // Now do PING checks on all servers
184                 // Only ping if this server needs one
185                 if (curtime >= s->NextPingTime())
186                 {
187                         // And if they answered the last
188                         if (s->AnsweredLastPing())
189                         {
190                                 // They did, send a ping to them
191                                 s->SetNextPingTime(curtime + Utils->PingFreq);
192                                 s->GetSocket()->WriteLine(CmdBuilder("PING").push(s->GetID()));
193                                 s->LastPingMsec = ts;
194                         }
195                         else
196                         {
197                                 // They didn't answer the last ping, if they are locally connected, get rid of them.
198                                 if (s->IsLocal())
199                                 {
200                                         TreeSocket* sock = s->GetSocket();
201                                         sock->SendError("Ping timeout");
202                                         sock->Close();
203                                         goto restart;
204                                 }
205                         }
206                 }
207
208                 // If warn on ping enabled and not warned and the difference is sufficient and they didn't answer the last ping...
209                 if ((Utils->PingWarnTime) && (!s->Warned) && (curtime >= s->NextPingTime() - (Utils->PingFreq - Utils->PingWarnTime)) && (!s->AnsweredLastPing()))
210                 {
211                         /* The server hasnt responded, send a warning to opers */
212                         ServerInstance->SNO->WriteToSnoMask('l',"Server \002%s\002 has not responded to PING for %d seconds, high latency.", s->GetName().c_str(), Utils->PingWarnTime);
213                         s->Warned = true;
214                 }
215         }
216 }
217
218 void ModuleSpanningTree::ConnectServer(Autoconnect* a, bool on_timer)
219 {
220         if (!a)
221                 return;
222         for(unsigned int j=0; j < a->servers.size(); j++)
223         {
224                 if (Utils->FindServer(a->servers[j]))
225                 {
226                         // found something in this block. Should the server fail,
227                         // we want to start at the start of the list, not in the
228                         // middle where we left off
229                         a->position = -1;
230                         return;
231                 }
232         }
233         if (on_timer && a->position >= 0)
234                 return;
235         if (!on_timer && a->position < 0)
236                 return;
237
238         a->position++;
239         while (a->position < (int)a->servers.size())
240         {
241                 Link* x = Utils->FindLink(a->servers[a->position]);
242                 if (x)
243                 {
244                         ServerInstance->SNO->WriteToSnoMask('l', "AUTOCONNECT: Auto-connecting server \002%s\002", x->Name.c_str());
245                         ConnectServer(x, a);
246                         return;
247                 }
248                 a->position++;
249         }
250         // Autoconnect chain has been fully iterated; start at the beginning on the
251         // next AutoConnectServers run
252         a->position = -1;
253 }
254
255 void ModuleSpanningTree::ConnectServer(Link* x, Autoconnect* y)
256 {
257         bool ipvalid = true;
258
259         if (InspIRCd::Match(ServerInstance->Config->ServerName, assign(x->Name), rfc_case_insensitive_map))
260         {
261                 ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Not connecting to myself.");
262                 return;
263         }
264
265         DNS::QueryType start_type = DNS::QUERY_AAAA;
266         if (strchr(x->IPAddr.c_str(),':'))
267         {
268                 in6_addr n;
269                 if (inet_pton(AF_INET6, x->IPAddr.c_str(), &n) < 1)
270                         ipvalid = false;
271         }
272         else
273         {
274                 in_addr n;
275                 if (inet_aton(x->IPAddr.c_str(),&n) < 1)
276                         ipvalid = false;
277         }
278
279         /* Do we already have an IP? If so, no need to resolve it. */
280         if (ipvalid)
281         {
282                 /* Gave a hook, but it wasnt one we know */
283                 TreeSocket* newsocket = new TreeSocket(x, y, x->IPAddr);
284                 if (newsocket->GetFd() > -1)
285                 {
286                         /* Handled automatically on success */
287                 }
288                 else
289                 {
290                         ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: %s.",
291                                 x->Name.c_str(), newsocket->getError().c_str());
292                         ServerInstance->GlobalCulls.AddItem(newsocket);
293                 }
294         }
295         else if (!DNS)
296         {
297                 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());
298         }
299         else
300         {
301                 ServernameResolver* snr = new ServernameResolver(*DNS, x->IPAddr, x, start_type, y);
302                 try
303                 {
304                         DNS->Process(snr);
305                 }
306                 catch (DNS::Exception& e)
307                 {
308                         delete snr;
309                         ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(), e.GetReason().c_str());
310                         ConnectServer(y, false);
311                 }
312         }
313 }
314
315 void ModuleSpanningTree::AutoConnectServers(time_t curtime)
316 {
317         for (std::vector<reference<Autoconnect> >::iterator i = Utils->AutoconnectBlocks.begin(); i < Utils->AutoconnectBlocks.end(); ++i)
318         {
319                 Autoconnect* x = *i;
320                 if (curtime >= x->NextConnectTime)
321                 {
322                         x->NextConnectTime = curtime + x->Period;
323                         ConnectServer(x, true);
324                 }
325         }
326 }
327
328 void ModuleSpanningTree::DoConnectTimeout(time_t curtime)
329 {
330         std::map<TreeSocket*, std::pair<std::string, int> >::iterator i = Utils->timeoutlist.begin();
331         while (i != Utils->timeoutlist.end())
332         {
333                 TreeSocket* s = i->first;
334                 std::pair<std::string, int> p = i->second;
335                 std::map<TreeSocket*, std::pair<std::string, int> >::iterator me = i;
336                 i++;
337                 if (s->GetLinkState() == DYING)
338                 {
339                         Utils->timeoutlist.erase(me);
340                         s->Close();
341                 }
342                 else if (curtime > s->age + p.second)
343                 {
344                         ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002 (timeout of %d seconds)",p.first.c_str(),p.second);
345                         Utils->timeoutlist.erase(me);
346                         s->Close();
347                 }
348         }
349 }
350
351 ModResult ModuleSpanningTree::HandleVersion(const std::vector<std::string>& parameters, User* user)
352 {
353         // we've already checked if pcnt > 0, so this is safe
354         TreeServer* found = Utils->FindServerMask(parameters[0]);
355         if (found)
356         {
357                 if (found == Utils->TreeRoot)
358                 {
359                         // Pass to default VERSION handler.
360                         return MOD_RES_PASSTHRU;
361                 }
362
363                 // If an oper wants to see the version then show the full version string instead of the normal,
364                 // but only if it is non-empty.
365                 // If it's empty it might be that the server is still syncing (full version hasn't arrived yet)
366                 // or the server is a 2.0 server and does not send a full version.
367                 bool showfull = ((user->IsOper()) && (!found->GetFullVersion().empty()));
368                 const std::string& Version = (showfull ? found->GetFullVersion() : found->GetVersion());
369                 user->WriteNumeric(RPL_VERSION, ":%s", Version.c_str());
370         }
371         else
372         {
373                 user->WriteNumeric(ERR_NOSUCHSERVER, "%s :No such server", parameters[0].c_str());
374         }
375         return MOD_RES_DENY;
376 }
377
378 /* This method will attempt to get a message to a remote user.
379  */
380 void ModuleSpanningTree::RemoteMessage(User* user, const char* format, ...)
381 {
382         std::string text;
383         VAFORMAT(text, format, format);
384
385         if (IS_LOCAL(user))
386                 user->WriteNotice(text);
387         else
388                 ServerInstance->PI->SendUserNotice(user, text);
389 }
390
391 ModResult ModuleSpanningTree::HandleConnect(const std::vector<std::string>& parameters, User* user)
392 {
393         for (std::vector<reference<Link> >::iterator i = Utils->LinkBlocks.begin(); i < Utils->LinkBlocks.end(); i++)
394         {
395                 Link* x = *i;
396                 if (InspIRCd::Match(x->Name.c_str(),parameters[0], rfc_case_insensitive_map))
397                 {
398                         if (InspIRCd::Match(ServerInstance->Config->ServerName, assign(x->Name), rfc_case_insensitive_map))
399                         {
400                                 RemoteMessage(user, "*** CONNECT: Server \002%s\002 is ME, not connecting.",x->Name.c_str());
401                                 return MOD_RES_DENY;
402                         }
403
404                         TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
405                         if (!CheckDupe)
406                         {
407                                 RemoteMessage(user, "*** CONNECT: Connecting to server: \002%s\002 (%s:%d)",x->Name.c_str(),(x->HiddenFromStats ? "<hidden>" : x->IPAddr.c_str()),x->Port);
408                                 ConnectServer(x);
409                                 return MOD_RES_DENY;
410                         }
411                         else
412                         {
413                                 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());
414                                 return MOD_RES_DENY;
415                         }
416                 }
417         }
418         RemoteMessage(user, "*** CONNECT: No server matching \002%s\002 could be found in the config file.",parameters[0].c_str());
419         return MOD_RES_DENY;
420 }
421
422 void ModuleSpanningTree::On005Numeric(std::map<std::string, std::string>& tokens)
423 {
424         tokens["MAP"];
425 }
426
427 void ModuleSpanningTree::OnUserInvite(User* source,User* dest,Channel* channel, time_t expiry)
428 {
429         if (IS_LOCAL(source))
430         {
431                 CmdBuilder params(source, "INVITE");
432                 params.push_back(dest->uuid);
433                 params.push_back(channel->name);
434                 params.push_int(channel->age);
435                 params.push_back(ConvToStr(expiry));
436                 params.Broadcast();
437         }
438 }
439
440 void ModuleSpanningTree::OnPostTopicChange(User* user, Channel* chan, const std::string &topic)
441 {
442         // Drop remote events on the floor.
443         if (!IS_LOCAL(user))
444                 return;
445
446         CommandFTopic::Builder(user, chan).Broadcast();
447 }
448
449 void ModuleSpanningTree::OnUserMessage(User* user, void* dest, int target_type, const std::string& text, char status, const CUList& exempt_list, MessageType msgtype)
450 {
451         if (!IS_LOCAL(user))
452                 return;
453
454         const char* message_type = (msgtype == MSG_PRIVMSG ? "PRIVMSG" : "NOTICE");
455         if (target_type == TYPE_USER)
456         {
457                 User* d = (User*) dest;
458                 if (!IS_LOCAL(d))
459                 {
460                         CmdBuilder params(user, message_type);
461                         params.push_back(d->uuid);
462                         params.push_last(text);
463                         params.Unicast(d);
464                 }
465         }
466         else if (target_type == TYPE_CHANNEL)
467         {
468                 Utils->SendChannelMessage(user->uuid, (Channel*)dest, text, status, exempt_list, message_type);
469         }
470         else if (target_type == TYPE_SERVER)
471         {
472                 char* target = (char*) dest;
473                 CmdBuilder par(user, message_type);
474                 par.push_back(target);
475                 par.push_last(text);
476                 par.Broadcast();
477         }
478 }
479
480 void ModuleSpanningTree::OnBackgroundTimer(time_t curtime)
481 {
482         AutoConnectServers(curtime);
483         DoPingChecks(curtime);
484         DoConnectTimeout(curtime);
485 }
486
487 void ModuleSpanningTree::OnUserConnect(LocalUser* user)
488 {
489         if (user->quitting)
490                 return;
491
492         CommandUID::Builder(user).Broadcast();
493
494         if (user->IsOper())
495                 CommandOpertype::Builder(user).Broadcast();
496
497         for(Extensible::ExtensibleStore::const_iterator i = user->GetExtList().begin(); i != user->GetExtList().end(); i++)
498         {
499                 ExtensionItem* item = i->first;
500                 std::string value = item->serialize(FORMAT_NETWORK, user, i->second);
501                 if (!value.empty())
502                         ServerInstance->PI->SendMetaData(user, item->name, value);
503         }
504
505         Utils->TreeRoot->UserCount++;
506 }
507
508 void ModuleSpanningTree::OnUserJoin(Membership* memb, bool sync, bool created_by_local, CUList& excepts)
509 {
510         // Only do this for local users
511         if (!IS_LOCAL(memb->user))
512                 return;
513
514         // Assign the current membership id to the new Membership and increase it
515         memb->id = currmembid++;
516
517         if (created_by_local)
518         {
519                 CommandFJoin::Builder params(memb->chan);
520                 params.add(memb);
521                 params.finalize();
522                 params.Broadcast();
523         }
524         else
525         {
526                 CmdBuilder params(memb->user, "IJOIN");
527                 params.push_back(memb->chan->name);
528                 params.push_int(memb->id);
529                 if (!memb->modes.empty())
530                 {
531                         params.push_back(ConvToStr(memb->chan->age));
532                         params.push_back(memb->modes);
533                 }
534                 params.Broadcast();
535         }
536 }
537
538 void ModuleSpanningTree::OnChangeHost(User* user, const std::string &newhost)
539 {
540         if (user->registered != REG_ALL || !IS_LOCAL(user))
541                 return;
542
543         CmdBuilder(user, "FHOST").push(newhost).Broadcast();
544 }
545
546 void ModuleSpanningTree::OnChangeName(User* user, const std::string &gecos)
547 {
548         if (user->registered != REG_ALL || !IS_LOCAL(user))
549                 return;
550
551         CmdBuilder(user, "FNAME").push_last(gecos).Broadcast();
552 }
553
554 void ModuleSpanningTree::OnChangeIdent(User* user, const std::string &ident)
555 {
556         if ((user->registered != REG_ALL) || (!IS_LOCAL(user)))
557                 return;
558
559         CmdBuilder(user, "FIDENT").push(ident).Broadcast();
560 }
561
562 void ModuleSpanningTree::OnUserPart(Membership* memb, std::string &partmessage, CUList& excepts)
563 {
564         if (IS_LOCAL(memb->user))
565         {
566                 CmdBuilder params(memb->user, "PART");
567                 params.push_back(memb->chan->name);
568                 if (!partmessage.empty())
569                         params.push_last(partmessage);
570                 params.Broadcast();
571         }
572 }
573
574 void ModuleSpanningTree::OnUserQuit(User* user, const std::string &reason, const std::string &oper_message)
575 {
576         if (IS_LOCAL(user))
577         {
578                 if (oper_message != reason)
579                         ServerInstance->PI->SendMetaData(user, "operquit", oper_message);
580
581                 CmdBuilder(user, "QUIT").push_last(reason).Broadcast();
582         }
583         else
584         {
585                 // Hide the message if one of the following is true:
586                 // - User is being quit due to a netsplit and quietbursts is on
587                 // - Server is a silent uline
588                 bool hide = (((this->SplitInProgress) && (Utils->quiet_bursts)) || (user->server->IsSilentULine()));
589                 if (!hide)
590                 {
591                         ServerInstance->SNO->WriteToSnoMask('Q', "Client exiting on server %s: %s (%s) [%s]",
592                                 user->server->GetName().c_str(), user->GetFullRealHost().c_str(), user->GetIPString().c_str(), oper_message.c_str());
593                 }
594         }
595
596         // Regardless, We need to modify the user Counts..
597         TreeServer::Get(user)->UserCount--;
598 }
599
600 void ModuleSpanningTree::OnUserPostNick(User* user, const std::string &oldnick)
601 {
602         if (IS_LOCAL(user))
603         {
604                 // The nick TS is updated by the core, we don't do it
605                 CmdBuilder params(user, "NICK");
606                 params.push_back(user->nick);
607                 params.push_back(ConvToStr(user->age));
608                 params.Broadcast();
609         }
610         else if (!loopCall && user->nick == user->uuid)
611         {
612                 CmdBuilder params("SAVE");
613                 params.push_back(user->uuid);
614                 params.push_back(ConvToStr(user->age));
615                 params.Broadcast();
616         }
617 }
618
619 void ModuleSpanningTree::OnUserKick(User* source, Membership* memb, const std::string &reason, CUList& excepts)
620 {
621         if ((!IS_LOCAL(source)) && (source != ServerInstance->FakeClient))
622                 return;
623
624         CmdBuilder params(source, "KICK");
625         params.push_back(memb->chan->name);
626         params.push_back(memb->user->uuid);
627         // If a remote user is being kicked by us then send the membership id in the kick too
628         if (!IS_LOCAL(memb->user))
629                 params.push_int(memb->id);
630         params.push_last(reason);
631         params.Broadcast();
632 }
633
634 void ModuleSpanningTree::OnPreRehash(User* user, const std::string &parameter)
635 {
636         if (loopCall)
637                 return; // Don't generate a REHASH here if we're in the middle of processing a message that generated this one
638
639         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "OnPreRehash called with param %s", parameter.c_str());
640
641         // Send out to other servers
642         if (!parameter.empty() && parameter[0] != '-')
643         {
644                 CmdBuilder params((user ? user->uuid : ServerInstance->Config->GetSID()), "REHASH");
645                 params.push_back(parameter);
646                 params.Forward(user ? TreeServer::Get(user)->GetRoute() : NULL);
647         }
648 }
649
650 void ModuleSpanningTree::ReadConfig(ConfigStatus& status)
651 {
652         // Did this rehash change the description of this server?
653         const std::string& newdesc = ServerInstance->Config->ServerDesc;
654         if (newdesc != Utils->TreeRoot->GetDesc())
655         {
656                 // Broadcast a SINFO desc message to let the network know about the new description. This is the description
657                 // string that is sent in the SERVER message initially and shown for example in WHOIS.
658                 // We don't need to update the field itself in the Server object - the core does that.
659                 CommandSInfo::Builder(Utils->TreeRoot, "desc", newdesc).Broadcast();
660         }
661
662         // Re-read config stuff
663         try
664         {
665                 Utils->ReadConfiguration();
666         }
667         catch (ModuleException& e)
668         {
669                 // Refresh the IP cache anyway, so servers read before the error will be allowed to connect
670                 Utils->RefreshIPCache();
671                 // Always warn local opers with snomask +l, also warn globally (snomask +L) if the rehash was issued by a remote user
672                 std::string msg = "Error in configuration: ";
673                 msg.append(e.GetReason());
674                 ServerInstance->SNO->WriteToSnoMask('l', msg);
675                 if (status.srcuser && !IS_LOCAL(status.srcuser))
676                         ServerInstance->PI->SendSNONotice('L', msg);
677         }
678 }
679
680 void ModuleSpanningTree::OnLoadModule(Module* mod)
681 {
682         std::string data;
683         data.push_back('+');
684         data.append(mod->ModuleSourceFile);
685         Version v = mod->GetVersion();
686         if (!v.link_data.empty())
687         {
688                 data.push_back('=');
689                 data.append(v.link_data);
690         }
691         ServerInstance->PI->SendMetaData("modules", data);
692 }
693
694 void ModuleSpanningTree::OnUnloadModule(Module* mod)
695 {
696         if (!Utils)
697                 return;
698         ServerInstance->PI->SendMetaData("modules", "-" + mod->ModuleSourceFile);
699
700         // Close all connections which use an IO hook provided by this module
701         const TreeServer::ChildServers& list = Utils->TreeRoot->GetChildren();
702         for (TreeServer::ChildServers::const_iterator i = list.begin(); i != list.end(); ++i)
703         {
704                 TreeSocket* sock = (*i)->GetSocket();
705                 if (sock->GetIOHook() && sock->GetIOHook()->prov->creator == mod)
706                 {
707                         sock->SendError("SSL module unloaded");
708                         sock->Close();
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)