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