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