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