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