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