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