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