]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/main.cpp
Fix broken linking over IPv4 on IPv6 capable systems.
[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 #include "modules/server.h"
29
30 #include "resolvers.h"
31 #include "main.h"
32 #include "utils.h"
33 #include "treeserver.h"
34 #include "link.h"
35 #include "treesocket.h"
36 #include "commands.h"
37 #include "translate.h"
38
39 ModuleSpanningTree::ModuleSpanningTree()
40         : Away::EventListener(this)
41         , Stats::EventListener(this)
42         , rconnect(this)
43         , rsquit(this)
44         , map(this)
45         , commands(this)
46         , currmembid(0)
47         , eventprov(this, "event/server")
48         , sslapi(this)
49         , DNS(this, "DNS")
50         , tagevprov(this, "event/messagetag")
51         , loopCall(false)
52 {
53 }
54
55 SpanningTreeCommands::SpanningTreeCommands(ModuleSpanningTree* module)
56         : svsjoin(module), svspart(module), svsnick(module), metadata(module),
57         uid(module), opertype(module), fjoin(module), ijoin(module), resync(module),
58         fmode(module), ftopic(module), fhost(module), fident(module), fname(module),
59         away(module), addline(module), delline(module), encap(module), idle(module),
60         nick(module), ping(module), pong(module), save(module),
61         server(module), squit(module), snonotice(module),
62         endburst(module), sinfo(module), num(module)
63 {
64 }
65
66 namespace
67 {
68         void SetLocalUsersServer(Server* newserver)
69         {
70                 // Does not change the server of quitting users because those are not in the list
71
72                 ServerInstance->FakeClient->server = newserver;
73                 const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
74                 for (UserManager::LocalList::const_iterator i = list.begin(); i != list.end(); ++i)
75                         (*i)->server = newserver;
76         }
77
78         void ResetMembershipIds()
79         {
80                 // Set all membership ids to 0
81                 const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
82                 for (UserManager::LocalList::iterator i = list.begin(); i != list.end(); ++i)
83                 {
84                         LocalUser* user = *i;
85                         for (User::ChanList::iterator j = user->chans.begin(); j != user->chans.end(); ++j)
86                                 (*j)->id = 0;
87                 }
88         }
89 }
90
91 void ModuleSpanningTree::init()
92 {
93         ServerInstance->SNO->EnableSnomask('l', "LINK");
94
95         ResetMembershipIds();
96
97         Utils = new SpanningTreeUtilities(this);
98         Utils->TreeRoot = new TreeServer;
99
100         ServerInstance->PI = &protocolinterface;
101
102         delete ServerInstance->FakeClient->server;
103         SetLocalUsersServer(Utils->TreeRoot);
104 }
105
106 void ModuleSpanningTree::ShowLinks(TreeServer* Current, User* user, int hops)
107 {
108         std::string Parent = Utils->TreeRoot->GetName();
109         if (Current->GetParent())
110         {
111                 Parent = Current->GetParent()->GetName();
112         }
113
114         const TreeServer::ChildServers& children = Current->GetChildren();
115         for (TreeServer::ChildServers::const_iterator i = children.begin(); i != children.end(); ++i)
116         {
117                 TreeServer* server = *i;
118                 if ((server->Hidden) || ((Utils->HideULines) && (server->IsULine())))
119                 {
120                         if (user->IsOper())
121                         {
122                                  ShowLinks(server, user, hops+1);
123                         }
124                 }
125                 else
126                 {
127                         ShowLinks(server, user, hops+1);
128                 }
129         }
130         /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
131         if ((Utils->HideULines) && (Current->IsULine()) && (!user->IsOper()))
132                 return;
133         /* Or if the server is hidden and they're not an oper */
134         else if ((Current->Hidden) && (!user->IsOper()))
135                 return;
136
137         user->WriteNumeric(RPL_LINKS, Current->GetName(),
138                         (((Utils->FlatLinks) && (!user->IsOper())) ? ServerInstance->Config->ServerName : Parent),
139                         InspIRCd::Format("%d %s", (((Utils->FlatLinks) && (!user->IsOper())) ? 0 : hops), Current->GetDesc().c_str()));
140 }
141
142 void ModuleSpanningTree::HandleLinks(const CommandBase::Params& parameters, User* user)
143 {
144         ShowLinks(Utils->TreeRoot,user,0);
145         user->WriteNumeric(RPL_ENDOFLINKS, '*', "End of /LINKS list.");
146 }
147
148 std::string ModuleSpanningTree::TimeToStr(time_t secs)
149 {
150         time_t mins_up = secs / 60;
151         time_t hours_up = mins_up / 60;
152         time_t days_up = hours_up / 24;
153         secs = secs % 60;
154         mins_up = mins_up % 60;
155         hours_up = hours_up % 24;
156         return ((days_up ? (ConvToStr(days_up) + "d") : "")
157                         + (hours_up ? (ConvToStr(hours_up) + "h") : "")
158                         + (mins_up ? (ConvToStr(mins_up) + "m") : "")
159                         + ConvToStr(secs) + "s");
160 }
161
162 void ModuleSpanningTree::ConnectServer(Autoconnect* a, bool on_timer)
163 {
164         if (!a)
165                 return;
166         for(unsigned int j=0; j < a->servers.size(); j++)
167         {
168                 if (Utils->FindServer(a->servers[j]))
169                 {
170                         // found something in this block. Should the server fail,
171                         // we want to start at the start of the list, not in the
172                         // middle where we left off
173                         a->position = -1;
174                         return;
175                 }
176         }
177         if (on_timer && a->position >= 0)
178                 return;
179         if (!on_timer && a->position < 0)
180                 return;
181
182         a->position++;
183         while (a->position < (int)a->servers.size())
184         {
185                 Link* x = Utils->FindLink(a->servers[a->position]);
186                 if (x)
187                 {
188                         ServerInstance->SNO->WriteToSnoMask('l', "AUTOCONNECT: Auto-connecting server \002%s\002", x->Name.c_str());
189                         ConnectServer(x, a);
190                         return;
191                 }
192                 a->position++;
193         }
194         // Autoconnect chain has been fully iterated; start at the beginning on the
195         // next AutoConnectServers run
196         a->position = -1;
197 }
198
199 void ModuleSpanningTree::ConnectServer(Link* x, Autoconnect* y)
200 {
201         if (InspIRCd::Match(ServerInstance->Config->ServerName, x->Name, ascii_case_insensitive_map))
202         {
203                 ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Not connecting to myself.");
204                 return;
205         }
206
207         irc::sockets::sockaddrs sa;
208 #ifndef _WIN32
209         if (x->IPAddr.find('/') != std::string::npos)
210         {
211                 struct stat sb;
212                 if (stat(x->IPAddr.c_str(), &sb) == -1 || !S_ISSOCK(sb.st_mode) || !irc::sockets::untosa(x->IPAddr, sa))
213                 {
214                         // We don't use the family() != AF_UNSPEC check below for UNIX sockets as
215                         // that results in a DNS lookup.
216                         ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: %s is not a UNIX socket!",
217                                 x->Name.c_str(), x->IPAddr.c_str());
218                         return;
219                 }
220         }
221         else
222 #endif
223         {
224                 // If this fails then the IP sa will be AF_UNSPEC.
225                 irc::sockets::aptosa(x->IPAddr, x->Port, sa);
226         }
227         
228         /* Do we already have an IP? If so, no need to resolve it. */
229         if (sa.family() != AF_UNSPEC)
230         {
231                 // Create a TreeServer object that will start connecting immediately in the background
232                 TreeSocket* newsocket = new TreeSocket(x, y, sa);
233                 if (newsocket->GetFd() > -1)
234                 {
235                         /* Handled automatically on success */
236                 }
237                 else
238                 {
239                         ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: %s.",
240                                 x->Name.c_str(), newsocket->getError().c_str());
241                         ServerInstance->GlobalCulls.AddItem(newsocket);
242                 }
243         }
244         else if (!DNS)
245         {
246                 ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: Hostname given and core_dns is not loaded, unable to resolve.", x->Name.c_str());
247         }
248         else
249         {
250                 // Guess start_type from bindip aftype
251                 DNS::QueryType start_type = DNS::QUERY_AAAA;
252                 irc::sockets::sockaddrs bind;
253                 if ((!x->Bind.empty()) && (irc::sockets::aptosa(x->Bind, 0, bind)))
254                 {
255                         if (bind.family() == AF_INET)
256                                 start_type = DNS::QUERY_A;
257                 }
258
259                 ServernameResolver* snr = new ServernameResolver(*DNS, x->IPAddr, x, start_type, y);
260                 try
261                 {
262                         DNS->Process(snr);
263                 }
264                 catch (DNS::Exception& e)
265                 {
266                         delete snr;
267                         ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(), e.GetReason().c_str());
268                         ConnectServer(y, false);
269                 }
270         }
271 }
272
273 void ModuleSpanningTree::AutoConnectServers(time_t curtime)
274 {
275         for (std::vector<reference<Autoconnect> >::iterator i = Utils->AutoconnectBlocks.begin(); i < Utils->AutoconnectBlocks.end(); ++i)
276         {
277                 Autoconnect* x = *i;
278                 if (curtime >= x->NextConnectTime)
279                 {
280                         x->NextConnectTime = curtime + x->Period;
281                         ConnectServer(x, true);
282                 }
283         }
284 }
285
286 void ModuleSpanningTree::DoConnectTimeout(time_t curtime)
287 {
288         SpanningTreeUtilities::TimeoutList::iterator i = Utils->timeoutlist.begin();
289         while (i != Utils->timeoutlist.end())
290         {
291                 TreeSocket* s = i->first;
292                 std::pair<std::string, unsigned int> p = i->second;
293                 SpanningTreeUtilities::TimeoutList::iterator me = i;
294                 i++;
295                 if (s->GetLinkState() == DYING)
296                 {
297                         Utils->timeoutlist.erase(me);
298                         s->Close();
299                 }
300                 else if (curtime > s->age + p.second)
301                 {
302                         ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002 (timeout of %u seconds)",p.first.c_str(),p.second);
303                         Utils->timeoutlist.erase(me);
304                         s->Close();
305                 }
306         }
307 }
308
309 ModResult ModuleSpanningTree::HandleVersion(const CommandBase::Params& parameters, User* user)
310 {
311         // We've already confirmed that !parameters.empty(), so this is safe
312         TreeServer* found = Utils->FindServerMask(parameters[0]);
313         if (found)
314         {
315                 if (found == Utils->TreeRoot)
316                 {
317                         // Pass to default VERSION handler.
318                         return MOD_RES_PASSTHRU;
319                 }
320
321                 // If an oper wants to see the version then show the full version string instead of the normal,
322                 // but only if it is non-empty.
323                 // If it's empty it might be that the server is still syncing (full version hasn't arrived yet)
324                 // or the server is a 2.0 server and does not send a full version.
325                 bool showfull = ((user->IsOper()) && (!found->GetFullVersion().empty()));
326
327                 Numeric::Numeric numeric(RPL_VERSION);
328                 irc::tokenstream tokens(showfull ? found->GetFullVersion() : found->GetVersion());
329                 for (std::string token; tokens.GetTrailing(token); )
330                         numeric.push(token);
331                 user->WriteNumeric(numeric);
332         }
333         else
334         {
335                 user->WriteNumeric(ERR_NOSUCHSERVER, parameters[0], "No such server");
336         }
337         return MOD_RES_DENY;
338 }
339
340 ModResult ModuleSpanningTree::HandleConnect(const CommandBase::Params& parameters, User* user)
341 {
342         for (std::vector<reference<Link> >::iterator i = Utils->LinkBlocks.begin(); i < Utils->LinkBlocks.end(); i++)
343         {
344                 Link* x = *i;
345                 if (InspIRCd::Match(x->Name, parameters[0], ascii_case_insensitive_map))
346                 {
347                         if (InspIRCd::Match(ServerInstance->Config->ServerName, x->Name, ascii_case_insensitive_map))
348                         {
349                                 user->WriteRemoteNotice(InspIRCd::Format("*** CONNECT: Server \002%s\002 is ME, not connecting.", x->Name.c_str()));
350                                 return MOD_RES_DENY;
351                         }
352
353                         TreeServer* CheckDupe = Utils->FindServer(x->Name);
354                         if (!CheckDupe)
355                         {
356                                 user->WriteRemoteNotice(InspIRCd::Format("*** CONNECT: Connecting to server: \002%s\002 (%s:%d)", x->Name.c_str(), (x->HiddenFromStats ? "<hidden>" : x->IPAddr.c_str()), x->Port));
357                                 ConnectServer(x);
358                                 return MOD_RES_DENY;
359                         }
360                         else
361                         {
362                                 user->WriteRemoteNotice(InspIRCd::Format("*** 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()));
363                                 return MOD_RES_DENY;
364                         }
365                 }
366         }
367         user->WriteRemoteNotice(InspIRCd::Format("*** CONNECT: No server matching \002%s\002 could be found in the config file.", parameters[0].c_str()));
368         return MOD_RES_DENY;
369 }
370
371 void ModuleSpanningTree::OnUserInvite(User* source, User* dest, Channel* channel, time_t expiry, unsigned int notifyrank, CUList& notifyexcepts)
372 {
373         if (IS_LOCAL(source))
374         {
375                 CmdBuilder params(source, "INVITE");
376                 params.push_back(dest->uuid);
377                 params.push_back(channel->name);
378                 params.push_int(channel->age);
379                 params.push_back(ConvToStr(expiry));
380                 params.Broadcast();
381         }
382 }
383
384 ModResult ModuleSpanningTree::OnPreTopicChange(User* user, Channel* chan, const std::string& topic)
385 {
386         // XXX: Deny topic changes if the current topic set time is the current time or is in the future because
387         // other servers will drop our FTOPIC. This restriction will be removed when the protocol is updated.
388         if ((chan->topicset >= ServerInstance->Time()) && (Utils->serverlist.size() > 1))
389         {
390                 user->WriteNumeric(ERR_CHANOPRIVSNEEDED, chan->name, "Retry topic change later");
391                 return MOD_RES_DENY;
392         }
393         return MOD_RES_PASSTHRU;
394 }
395
396 void ModuleSpanningTree::OnPostTopicChange(User* user, Channel* chan, const std::string &topic)
397 {
398         // Drop remote events on the floor.
399         if (!IS_LOCAL(user))
400                 return;
401
402         CommandFTopic::Builder(user, chan).Broadcast();
403 }
404
405 void ModuleSpanningTree::OnUserPostMessage(User* user, const MessageTarget& target, const MessageDetails& details)
406 {
407         if (!IS_LOCAL(user))
408                 return;
409
410         const char* message_type = (details.type == MSG_PRIVMSG ? "PRIVMSG" : "NOTICE");
411         if (target.type == MessageTarget::TYPE_USER)
412         {
413                 User* d = target.Get<User>();
414                 if (!IS_LOCAL(d))
415                 {
416                         CmdBuilder params(user, message_type);
417                         params.push_tags(details.tags_out);
418                         params.push_back(d->uuid);
419                         params.push_last(details.text);
420                         params.Unicast(d);
421                 }
422         }
423         else if (target.type == MessageTarget::TYPE_CHANNEL)
424         {
425                 Utils->SendChannelMessage(user->uuid, target.Get<Channel>(), details.text, target.status, details.tags_out, details.exemptions, message_type);
426         }
427         else if (target.type == MessageTarget::TYPE_SERVER)
428         {
429                 const std::string* serverglob = target.Get<std::string>();
430                 CmdBuilder par(user, message_type);
431                 par.push_tags(details.tags_out);
432                 par.push_back(*serverglob);
433                 par.push_last(details.text);
434                 par.Broadcast();
435         }
436 }
437
438 void ModuleSpanningTree::OnBackgroundTimer(time_t curtime)
439 {
440         AutoConnectServers(curtime);
441         DoConnectTimeout(curtime);
442 }
443
444 void ModuleSpanningTree::OnUserConnect(LocalUser* user)
445 {
446         if (user->quitting)
447                 return;
448
449         // Create the lazy ssl_cert metadata for this user if not already created.
450         if (sslapi)
451                 sslapi->GetCertificate(user);
452
453         CommandUID::Builder(user).Broadcast();
454
455         if (user->IsOper())
456                 CommandOpertype::Builder(user).Broadcast();
457
458         for(Extensible::ExtensibleStore::const_iterator i = user->GetExtList().begin(); i != user->GetExtList().end(); i++)
459         {
460                 ExtensionItem* item = i->first;
461                 std::string value = item->serialize(FORMAT_NETWORK, user, i->second);
462                 if (!value.empty())
463                         ServerInstance->PI->SendMetaData(user, item->name, value);
464         }
465
466         Utils->TreeRoot->UserCount++;
467 }
468
469 void ModuleSpanningTree::OnUserJoin(Membership* memb, bool sync, bool created_by_local, CUList& excepts)
470 {
471         // Only do this for local users
472         if (!IS_LOCAL(memb->user))
473                 return;
474
475         // Assign the current membership id to the new Membership and increase it
476         memb->id = currmembid++;
477
478         if (created_by_local)
479         {
480                 CommandFJoin::Builder params(memb->chan);
481                 params.add(memb);
482                 params.finalize();
483                 params.Broadcast();
484         }
485         else
486         {
487                 CmdBuilder params(memb->user, "IJOIN");
488                 params.push_back(memb->chan->name);
489                 params.push_int(memb->id);
490                 if (!memb->modes.empty())
491                 {
492                         params.push_back(ConvToStr(memb->chan->age));
493                         params.push_back(memb->modes);
494                 }
495                 params.Broadcast();
496         }
497 }
498
499 void ModuleSpanningTree::OnChangeHost(User* user, const std::string &newhost)
500 {
501         if (user->registered != REG_ALL || !IS_LOCAL(user))
502                 return;
503
504         CmdBuilder(user, "FHOST").push(newhost).Broadcast();
505 }
506
507 void ModuleSpanningTree::OnChangeRealName(User* user, const std::string& real)
508 {
509         if (user->registered != REG_ALL || !IS_LOCAL(user))
510                 return;
511
512         CmdBuilder(user, "FNAME").push_last(real).Broadcast();
513 }
514
515 void ModuleSpanningTree::OnChangeIdent(User* user, const std::string &ident)
516 {
517         if ((user->registered != REG_ALL) || (!IS_LOCAL(user)))
518                 return;
519
520         CmdBuilder(user, "FIDENT").push(ident).Broadcast();
521 }
522
523 void ModuleSpanningTree::OnUserPart(Membership* memb, std::string &partmessage, CUList& excepts)
524 {
525         if (IS_LOCAL(memb->user))
526         {
527                 CmdBuilder params(memb->user, "PART");
528                 params.push_back(memb->chan->name);
529                 if (!partmessage.empty())
530                         params.push_last(partmessage);
531                 params.Broadcast();
532         }
533 }
534
535 void ModuleSpanningTree::OnUserQuit(User* user, const std::string &reason, const std::string &oper_message)
536 {
537         if (IS_LOCAL(user))
538         {
539                 if (oper_message != reason)
540                         ServerInstance->PI->SendMetaData(user, "operquit", oper_message);
541
542                 CmdBuilder(user, "QUIT").push_last(reason).Broadcast();
543         }
544         else
545         {
546                 // Hide the message if one of the following is true:
547                 // - User is being quit due to a netsplit and quietbursts is on
548                 // - Server is a silent uline
549                 TreeServer* server = TreeServer::Get(user);
550                 bool hide = (((server->IsDead()) && (Utils->quiet_bursts)) || (server->IsSilentULine()));
551                 if (!hide)
552                 {
553                         ServerInstance->SNO->WriteToSnoMask('Q', "Client exiting on server %s: %s (%s) [%s]",
554                                 user->server->GetName().c_str(), user->GetFullRealHost().c_str(), user->GetIPString().c_str(), oper_message.c_str());
555                 }
556         }
557
558         // Regardless, update the UserCount
559         TreeServer::Get(user)->UserCount--;
560 }
561
562 void ModuleSpanningTree::OnUserPostNick(User* user, const std::string &oldnick)
563 {
564         if (IS_LOCAL(user))
565         {
566                 // The nick TS is updated by the core, we don't do it
567                 CmdBuilder params(user, "NICK");
568                 params.push_back(user->nick);
569                 params.push_back(ConvToStr(user->age));
570                 params.Broadcast();
571         }
572         else if (!loopCall)
573         {
574                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: Changed nick of remote user %s from %s to %s TS %lu by ourselves!", user->uuid.c_str(), oldnick.c_str(), user->nick.c_str(), (unsigned long) user->age);
575         }
576 }
577
578 void ModuleSpanningTree::OnUserKick(User* source, Membership* memb, const std::string &reason, CUList& excepts)
579 {
580         if ((!IS_LOCAL(source)) && (source != ServerInstance->FakeClient))
581                 return;
582
583         CmdBuilder params(source, "KICK");
584         params.push_back(memb->chan->name);
585         params.push_back(memb->user->uuid);
586         // If a remote user is being kicked by us then send the membership id in the kick too
587         if (!IS_LOCAL(memb->user))
588                 params.push_int(memb->id);
589         params.push_last(reason);
590         params.Broadcast();
591 }
592
593 void ModuleSpanningTree::OnPreRehash(User* user, const std::string &parameter)
594 {
595         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "OnPreRehash called with param %s", parameter.c_str());
596
597         // Send out to other servers
598         if (!parameter.empty() && parameter[0] != '-')
599         {
600                 CmdBuilder params((user ? user->uuid : ServerInstance->Config->GetSID()), "REHASH");
601                 params.push_back(parameter);
602                 params.Forward(user ? TreeServer::Get(user)->GetRoute() : NULL);
603         }
604 }
605
606 void ModuleSpanningTree::ReadConfig(ConfigStatus& status)
607 {
608         // Did this rehash change the description of this server?
609         const std::string& newdesc = ServerInstance->Config->ServerDesc;
610         if (newdesc != Utils->TreeRoot->GetDesc())
611         {
612                 // Broadcast a SINFO desc message to let the network know about the new description. This is the description
613                 // string that is sent in the SERVER message initially and shown for example in WHOIS.
614                 // We don't need to update the field itself in the Server object - the core does that.
615                 CommandSInfo::Builder(Utils->TreeRoot, "desc", newdesc).Broadcast();
616         }
617
618         // Re-read config stuff
619         try
620         {
621                 Utils->ReadConfiguration();
622         }
623         catch (ModuleException& e)
624         {
625                 // Refresh the IP cache anyway, so servers read before the error will be allowed to connect
626                 Utils->RefreshIPCache();
627                 // Always warn local opers with snomask +l, also warn globally (snomask +L) if the rehash was issued by a remote user
628                 std::string msg = "Error in configuration: ";
629                 msg.append(e.GetReason());
630                 ServerInstance->SNO->WriteToSnoMask('l', msg);
631                 if (status.srcuser && !IS_LOCAL(status.srcuser))
632                         ServerInstance->PI->SendSNONotice('L', msg);
633         }
634 }
635
636 void ModuleSpanningTree::OnLoadModule(Module* mod)
637 {
638         std::string data;
639         data.push_back('+');
640         data.append(mod->ModuleSourceFile);
641         Version v = mod->GetVersion();
642         if (!v.link_data.empty())
643         {
644                 data.push_back('=');
645                 data.append(v.link_data);
646         }
647         ServerInstance->PI->SendMetaData("modules", data);
648 }
649
650 void ModuleSpanningTree::OnUnloadModule(Module* mod)
651 {
652         if (!Utils)
653                 return;
654         ServerInstance->PI->SendMetaData("modules", "-" + mod->ModuleSourceFile);
655
656         if (mod == this)
657         {
658                 // We are being unloaded, inform modules about all servers splitting which cannot be done later when the servers are actually disconnected
659                 const server_hash& servers = Utils->serverlist;
660                 for (server_hash::const_iterator i = servers.begin(); i != servers.end(); ++i)
661                 {
662                         TreeServer* server = i->second;
663                         if (!server->IsRoot())
664                                 FOREACH_MOD_CUSTOM(GetEventProvider(), ServerEventListener, OnServerSplit, (server));
665                 }
666                 return;
667         }
668
669         // Some other module is being unloaded. If it provides an IOHook we use, we must close that server connection now.
670
671 restart:
672         // Close all connections which use an IO hook provided by this module
673         const TreeServer::ChildServers& list = Utils->TreeRoot->GetChildren();
674         for (TreeServer::ChildServers::const_iterator i = list.begin(); i != list.end(); ++i)
675         {
676                 TreeSocket* sock = (*i)->GetSocket();
677                 if (sock->GetModHook(mod))
678                 {
679                         sock->SendError("SSL module unloaded");
680                         sock->Close();
681                         // XXX: The list we're iterating is modified by TreeServer::SQuit() which is called by Close()
682                         goto restart;
683                 }
684         }
685
686         for (SpanningTreeUtilities::TimeoutList::const_iterator i = Utils->timeoutlist.begin(); i != Utils->timeoutlist.end(); ++i)
687         {
688                 TreeSocket* sock = i->first;
689                 if (sock->GetModHook(mod))
690                         sock->Close();
691         }
692 }
693
694 void ModuleSpanningTree::OnOper(User* user, const std::string &opertype)
695 {
696         if (user->registered != REG_ALL || !IS_LOCAL(user))
697                 return;
698
699         // Note: The protocol does not allow direct umode +o;
700         // sending OPERTYPE infers +o modechange locally.
701         CommandOpertype::Builder(user).Broadcast();
702 }
703
704 void ModuleSpanningTree::OnAddLine(User* user, XLine *x)
705 {
706         if (!x->IsBurstable() || loopCall || (user && !IS_LOCAL(user)))
707                 return;
708
709         if (!user)
710                 user = ServerInstance->FakeClient;
711
712         CommandAddLine::Builder(x, user).Broadcast();
713 }
714
715 void ModuleSpanningTree::OnDelLine(User* user, XLine *x)
716 {
717         if (!x->IsBurstable() || loopCall || (user && !IS_LOCAL(user)))
718                 return;
719
720         if (!user)
721                 user = ServerInstance->FakeClient;
722
723         CmdBuilder params(user, "DELLINE");
724         params.push_back(x->type);
725         params.push_back(x->Displayable());
726         params.Broadcast();
727 }
728
729 void ModuleSpanningTree::OnUserAway(User* user)
730 {
731         if (IS_LOCAL(user))
732                 CommandAway::Builder(user).Broadcast();
733 }
734
735 void ModuleSpanningTree::OnUserBack(User* user)
736 {
737         if (IS_LOCAL(user))
738                 CommandAway::Builder(user).Broadcast();
739 }
740
741 void ModuleSpanningTree::OnMode(User* source, User* u, Channel* c, const Modes::ChangeList& modes, ModeParser::ModeProcessFlag processflags)
742 {
743         if (processflags & ModeParser::MODE_LOCALONLY)
744                 return;
745
746         if (u)
747         {
748                 if (u->registered != REG_ALL)
749                         return;
750
751                 CmdBuilder params(source, "MODE");
752                 params.push(u->uuid);
753                 params.push(ClientProtocol::Messages::Mode::ToModeLetters(modes));
754                 params.push_raw(Translate::ModeChangeListToParams(modes.getlist()));
755                 params.Broadcast();
756         }
757         else
758         {
759                 CmdBuilder params(source, "FMODE");
760                 params.push(c->name);
761                 params.push_int(c->age);
762                 params.push(ClientProtocol::Messages::Mode::ToModeLetters(modes));
763                 params.push_raw(Translate::ModeChangeListToParams(modes.getlist()));
764                 params.Broadcast();
765         }
766 }
767
768 CullResult ModuleSpanningTree::cull()
769 {
770         if (Utils)
771                 Utils->cull();
772         return this->Module::cull();
773 }
774
775 ModuleSpanningTree::~ModuleSpanningTree()
776 {
777         ServerInstance->PI = &ServerInstance->DefaultProtocolInterface;
778
779         Server* newsrv = new Server(ServerInstance->Config->ServerName, ServerInstance->Config->ServerDesc);
780         SetLocalUsersServer(newsrv);
781
782         delete Utils;
783 }
784
785 Version ModuleSpanningTree::GetVersion()
786 {
787         return Version("Allows servers to be linked", VF_VENDOR);
788 }
789
790 /* It is IMPORTANT that m_spanningtree is the last module in the chain
791  * so that any activity it sees is FINAL, e.g. we arent going to send out
792  * a NICK message before m_cloaking has finished putting the +x on the user,
793  * etc etc.
794  * Therefore, we set our priority to PRIORITY_LAST to make sure we end up at the END of
795  * the module call queue.
796  */
797 void ModuleSpanningTree::Prioritize()
798 {
799         ServerInstance->Modules->SetPriority(this, PRIORITY_LAST);
800         ServerInstance->Modules.SetPriority(this, I_OnPreTopicChange, PRIORITY_FIRST);
801 }
802
803 MODULE_INIT(ModuleSpanningTree)