]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/main.cpp
Pass an interface to the OnSync hooks
[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 "protocolinterface.h"
37
38 ModuleSpanningTree::ModuleSpanningTree()
39         : rconnect(this), rsquit(this), map(this)
40         , commands(NULL), DNS(this, "DNS")
41 {
42 }
43
44 SpanningTreeCommands::SpanningTreeCommands(ModuleSpanningTree* module)
45         : svsjoin(module), svspart(module), svsnick(module), metadata(module),
46         uid(module), opertype(module), fjoin(module), ijoin(module), resync(module),
47         fmode(module), ftopic(module), fhost(module), fident(module), fname(module),
48         away(module), addline(module), delline(module), encap(module), idle(module),
49         nick(module), ping(module), pong(module), push(module), save(module),
50         server(module), squit(module), snonotice(module), version(module),
51         burst(module), endburst(module)
52 {
53 }
54
55 void ModuleSpanningTree::init()
56 {
57         ServerInstance->SNO->EnableSnomask('l', "LINK");
58
59         Utils = new SpanningTreeUtilities(this);
60         Utils->TreeRoot = new TreeServer;
61         commands = new SpanningTreeCommands(this);
62
63         delete ServerInstance->PI;
64         ServerInstance->PI = new SpanningTreeProtocolInterface;
65         loopCall = false;
66
67         // update our local user count
68         Utils->TreeRoot->UserCount = ServerInstance->Users->local_users.size();
69 }
70
71 void ModuleSpanningTree::ShowLinks(TreeServer* Current, User* user, int hops)
72 {
73         std::string Parent = Utils->TreeRoot->GetName();
74         if (Current->GetParent())
75         {
76                 Parent = Current->GetParent()->GetName();
77         }
78
79         const TreeServer::ChildServers& children = Current->GetChildren();
80         for (TreeServer::ChildServers::const_iterator i = children.begin(); i != children.end(); ++i)
81         {
82                 TreeServer* server = *i;
83                 if ((server->Hidden) || ((Utils->HideULines) && (ServerInstance->ULine(server->GetName()))))
84                 {
85                         if (user->IsOper())
86                         {
87                                  ShowLinks(server, user, hops+1);
88                         }
89                 }
90                 else
91                 {
92                         ShowLinks(server, user, hops+1);
93                 }
94         }
95         /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
96         if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetName())) && (!user->IsOper()))
97                 return;
98         /* Or if the server is hidden and they're not an oper */
99         else if ((Current->Hidden) && (!user->IsOper()))
100                 return;
101
102         user->WriteNumeric(364, "%s %s %s :%d %s",      user->nick.c_str(), Current->GetName().c_str(),
103                         (Utils->FlatLinks && (!user->IsOper())) ? ServerInstance->Config->ServerName.c_str() : Parent.c_str(),
104                         (Utils->FlatLinks && (!user->IsOper())) ? 0 : hops,
105                         Current->GetDesc().c_str());
106 }
107
108 void ModuleSpanningTree::HandleLinks(const std::vector<std::string>& parameters, User* user)
109 {
110         ShowLinks(Utils->TreeRoot,user,0);
111         user->WriteNumeric(365, "%s * :End of /LINKS list.",user->nick.c_str());
112 }
113
114 std::string ModuleSpanningTree::TimeToStr(time_t secs)
115 {
116         time_t mins_up = secs / 60;
117         time_t hours_up = mins_up / 60;
118         time_t days_up = hours_up / 24;
119         secs = secs % 60;
120         mins_up = mins_up % 60;
121         hours_up = hours_up % 24;
122         return ((days_up ? (ConvToStr(days_up) + "d") : "")
123                         + (hours_up ? (ConvToStr(hours_up) + "h") : "")
124                         + (mins_up ? (ConvToStr(mins_up) + "m") : "")
125                         + ConvToStr(secs) + "s");
126 }
127
128 void ModuleSpanningTree::DoPingChecks(time_t curtime)
129 {
130         /*
131          * Cancel remote burst mode on any servers which still have it enabled due to latency/lack of data.
132          * This prevents lost REMOTECONNECT notices
133          */
134         long ts = ServerInstance->Time() * 1000 + (ServerInstance->Time_ns() / 1000000);
135
136 restart:
137         for (server_hash::iterator i = Utils->serverlist.begin(); i != Utils->serverlist.end(); i++)
138         {
139                 TreeServer *s = i->second;
140
141                 // Skip myself
142                 if (s->IsRoot())
143                         continue;
144
145                 if (s->GetSocket()->GetLinkState() == DYING)
146                 {
147                         s->GetSocket()->Close();
148                         goto restart;
149                 }
150
151                 // Do not ping servers that are not fully connected yet!
152                 // Servers which are connected to us have IsLocal() == true and if they're fully connected
153                 // then Socket->LinkState == CONNECTED. Servers that are linked to another server are always fully connected.
154                 if (s->IsLocal() && s->GetSocket()->GetLinkState() != CONNECTED)
155                         continue;
156
157                 // Now do PING checks on all servers
158                 // Only ping if this server needs one
159                 if (curtime >= s->NextPingTime())
160                 {
161                         // And if they answered the last
162                         if (s->AnsweredLastPing())
163                         {
164                                 // They did, send a ping to them
165                                 s->SetNextPingTime(curtime + Utils->PingFreq);
166                                 s->GetSocket()->WriteLine(":" + ServerInstance->Config->GetSID() + " PING " + s->GetID());
167                                 s->LastPingMsec = ts;
168                         }
169                         else
170                         {
171                                 // They didn't answer the last ping, if they are locally connected, get rid of them.
172                                 if (s->IsLocal())
173                                 {
174                                         TreeSocket* sock = s->GetSocket();
175                                         sock->SendError("Ping timeout");
176                                         sock->Close();
177                                         goto restart;
178                                 }
179                         }
180                 }
181
182                 // If warn on ping enabled and not warned and the difference is sufficient and they didn't answer the last ping...
183                 if ((Utils->PingWarnTime) && (!s->Warned) && (curtime >= s->NextPingTime() - (Utils->PingFreq - Utils->PingWarnTime)) && (!s->AnsweredLastPing()))
184                 {
185                         /* The server hasnt responded, send a warning to opers */
186                         ServerInstance->SNO->WriteToSnoMask('l',"Server \002%s\002 has not responded to PING for %d seconds, high latency.", s->GetName().c_str(), Utils->PingWarnTime);
187                         s->Warned = true;
188                 }
189         }
190 }
191
192 void ModuleSpanningTree::ConnectServer(Autoconnect* a, bool on_timer)
193 {
194         if (!a)
195                 return;
196         for(unsigned int j=0; j < a->servers.size(); j++)
197         {
198                 if (Utils->FindServer(a->servers[j]))
199                 {
200                         // found something in this block. Should the server fail,
201                         // we want to start at the start of the list, not in the
202                         // middle where we left off
203                         a->position = -1;
204                         return;
205                 }
206         }
207         if (on_timer && a->position >= 0)
208                 return;
209         if (!on_timer && a->position < 0)
210                 return;
211
212         a->position++;
213         while (a->position < (int)a->servers.size())
214         {
215                 Link* x = Utils->FindLink(a->servers[a->position]);
216                 if (x)
217                 {
218                         ServerInstance->SNO->WriteToSnoMask('l', "AUTOCONNECT: Auto-connecting server \002%s\002", x->Name.c_str());
219                         ConnectServer(x, a);
220                         return;
221                 }
222                 a->position++;
223         }
224         // Autoconnect chain has been fully iterated; start at the beginning on the
225         // next AutoConnectServers run
226         a->position = -1;
227 }
228
229 void ModuleSpanningTree::ConnectServer(Link* x, Autoconnect* y)
230 {
231         bool ipvalid = true;
232
233         if (InspIRCd::Match(ServerInstance->Config->ServerName, assign(x->Name)))
234         {
235                 ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Not connecting to myself.");
236                 return;
237         }
238
239         DNS::QueryType start_type = DNS::QUERY_AAAA;
240         if (strchr(x->IPAddr.c_str(),':'))
241         {
242                 in6_addr n;
243                 if (inet_pton(AF_INET6, x->IPAddr.c_str(), &n) < 1)
244                         ipvalid = false;
245         }
246         else
247         {
248                 in_addr n;
249                 if (inet_aton(x->IPAddr.c_str(),&n) < 1)
250                         ipvalid = false;
251         }
252
253         /* Do we already have an IP? If so, no need to resolve it. */
254         if (ipvalid)
255         {
256                 /* Gave a hook, but it wasnt one we know */
257                 TreeSocket* newsocket = new TreeSocket(x, y, x->IPAddr);
258                 if (newsocket->GetFd() > -1)
259                 {
260                         /* Handled automatically on success */
261                 }
262                 else
263                 {
264                         ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: %s.",
265                                 x->Name.c_str(), newsocket->getError().c_str());
266                         ServerInstance->GlobalCulls.AddItem(newsocket);
267                 }
268         }
269         else if (!DNS)
270         {
271                 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());
272         }
273         else
274         {
275                 ServernameResolver* snr = new ServernameResolver(*DNS, x->IPAddr, x, start_type, y);
276                 try
277                 {
278                         DNS->Process(snr);
279                 }
280                 catch (DNS::Exception& e)
281                 {
282                         delete snr;
283                         ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(), e.GetReason());
284                         ConnectServer(y, false);
285                 }
286         }
287 }
288
289 void ModuleSpanningTree::AutoConnectServers(time_t curtime)
290 {
291         for (std::vector<reference<Autoconnect> >::iterator i = Utils->AutoconnectBlocks.begin(); i < Utils->AutoconnectBlocks.end(); ++i)
292         {
293                 Autoconnect* x = *i;
294                 if (curtime >= x->NextConnectTime)
295                 {
296                         x->NextConnectTime = curtime + x->Period;
297                         ConnectServer(x, true);
298                 }
299         }
300 }
301
302 void ModuleSpanningTree::DoConnectTimeout(time_t curtime)
303 {
304         std::map<TreeSocket*, std::pair<std::string, int> >::iterator i = Utils->timeoutlist.begin();
305         while (i != Utils->timeoutlist.end())
306         {
307                 TreeSocket* s = i->first;
308                 std::pair<std::string, int> p = i->second;
309                 std::map<TreeSocket*, std::pair<std::string, int> >::iterator me = i;
310                 i++;
311                 if (s->GetLinkState() == DYING)
312                 {
313                         Utils->timeoutlist.erase(me);
314                         s->Close();
315                 }
316                 else if (curtime > s->age + p.second)
317                 {
318                         ServerInstance->SNO->WriteToSnoMask('l',"CONNECT: Error connecting \002%s\002 (timeout of %d seconds)",p.first.c_str(),p.second);
319                         Utils->timeoutlist.erase(me);
320                         s->Close();
321                 }
322         }
323 }
324
325 ModResult ModuleSpanningTree::HandleVersion(const std::vector<std::string>& parameters, User* user)
326 {
327         // we've already checked if pcnt > 0, so this is safe
328         TreeServer* found = Utils->FindServerMask(parameters[0]);
329         if (found)
330         {
331                 if (found == Utils->TreeRoot)
332                 {
333                         // Pass to default VERSION handler.
334                         return MOD_RES_PASSTHRU;
335                 }
336                 std::string Version = found->GetVersion();
337                 user->WriteNumeric(351, "%s :%s",user->nick.c_str(),Version.c_str());
338         }
339         else
340         {
341                 user->WriteNumeric(402, "%s %s :No such server",user->nick.c_str(),parameters[0].c_str());
342         }
343         return MOD_RES_DENY;
344 }
345
346 /* This method will attempt to get a message to a remote user.
347  */
348 void ModuleSpanningTree::RemoteMessage(User* user, const char* format, ...)
349 {
350         std::string text;
351         VAFORMAT(text, format, format);
352
353         if (IS_LOCAL(user))
354                 user->WriteNotice(text);
355         else
356                 ServerInstance->PI->SendUserNotice(user, text);
357 }
358
359 ModResult ModuleSpanningTree::HandleConnect(const std::vector<std::string>& parameters, User* user)
360 {
361         for (std::vector<reference<Link> >::iterator i = Utils->LinkBlocks.begin(); i < Utils->LinkBlocks.end(); i++)
362         {
363                 Link* x = *i;
364                 if (InspIRCd::Match(x->Name.c_str(),parameters[0]))
365                 {
366                         if (InspIRCd::Match(ServerInstance->Config->ServerName, assign(x->Name)))
367                         {
368                                 RemoteMessage(user, "*** CONNECT: Server \002%s\002 is ME, not connecting.",x->Name.c_str());
369                                 return MOD_RES_DENY;
370                         }
371
372                         TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
373                         if (!CheckDupe)
374                         {
375                                 RemoteMessage(user, "*** CONNECT: Connecting to server: \002%s\002 (%s:%d)",x->Name.c_str(),(x->HiddenFromStats ? "<hidden>" : x->IPAddr.c_str()),x->Port);
376                                 ConnectServer(x);
377                                 return MOD_RES_DENY;
378                         }
379                         else
380                         {
381                                 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());
382                                 return MOD_RES_DENY;
383                         }
384                 }
385         }
386         RemoteMessage(user, "*** CONNECT: No server matching \002%s\002 could be found in the config file.",parameters[0].c_str());
387         return MOD_RES_DENY;
388 }
389
390 void ModuleSpanningTree::On005Numeric(std::map<std::string, std::string>& tokens)
391 {
392         tokens["MAP"];
393 }
394
395 void ModuleSpanningTree::OnGetServerDescription(const std::string &servername,std::string &description)
396 {
397         TreeServer* s = Utils->FindServer(servername);
398         if (s)
399         {
400                 description = s->GetDesc();
401         }
402 }
403
404 void ModuleSpanningTree::OnUserInvite(User* source,User* dest,Channel* channel, time_t expiry)
405 {
406         if (IS_LOCAL(source))
407         {
408                 CmdBuilder params(source, "INVITE");
409                 params.push_back(dest->uuid);
410                 params.push_back(channel->name);
411                 params.push_back(ConvToStr(expiry));
412                 params.Broadcast();
413         }
414 }
415
416 void ModuleSpanningTree::OnPostTopicChange(User* user, Channel* chan, const std::string &topic)
417 {
418         // Drop remote events on the floor.
419         if (!IS_LOCAL(user))
420                 return;
421
422         CommandFTopic::Builder(user, chan).Broadcast();
423 }
424
425 void ModuleSpanningTree::OnUserMessage(User* user, void* dest, int target_type, const std::string& text, char status, const CUList& exempt_list, MessageType msgtype)
426 {
427         if (!IS_LOCAL(user))
428                 return;
429
430         const char* message_type = (msgtype == MSG_PRIVMSG ? "PRIVMSG" : "NOTICE");
431         if (target_type == TYPE_USER)
432         {
433                 User* d = (User*) dest;
434                 if (!IS_LOCAL(d))
435                 {
436                         CmdBuilder params(user, message_type);
437                         params.push_back(d->uuid);
438                         params.push_last(text);
439                         params.Unicast(d);
440                 }
441         }
442         else if (target_type == TYPE_CHANNEL)
443         {
444                 Utils->SendChannelMessage(user->uuid, (Channel*)dest, text, status, exempt_list, message_type);
445         }
446         else if (target_type == TYPE_SERVER)
447         {
448                 char* target = (char*) dest;
449                 CmdBuilder par(user, message_type);
450                 par.push_back(target);
451                 par.push_last(text);
452                 par.Broadcast();
453         }
454 }
455
456 void ModuleSpanningTree::OnBackgroundTimer(time_t curtime)
457 {
458         AutoConnectServers(curtime);
459         DoPingChecks(curtime);
460         DoConnectTimeout(curtime);
461 }
462
463 void ModuleSpanningTree::OnUserConnect(LocalUser* user)
464 {
465         if (user->quitting)
466                 return;
467
468         CommandUID::Builder(user).Broadcast();
469
470         if (user->IsOper())
471                 CommandOpertype::Builder(user).Broadcast();
472
473         for(Extensible::ExtensibleStore::const_iterator i = user->GetExtList().begin(); i != user->GetExtList().end(); i++)
474         {
475                 ExtensionItem* item = i->first;
476                 std::string value = item->serialize(FORMAT_NETWORK, user, i->second);
477                 if (!value.empty())
478                         ServerInstance->PI->SendMetaData(user, item->name, value);
479         }
480
481         Utils->TreeRoot->UserCount++;
482 }
483
484 void ModuleSpanningTree::OnUserJoin(Membership* memb, bool sync, bool created_by_local, CUList& excepts)
485 {
486         // Only do this for local users
487         if (!IS_LOCAL(memb->user))
488                 return;
489
490         if (created_by_local)
491         {
492                 CmdBuilder params("FJOIN");
493                 params.push_back(memb->chan->name);
494                 params.push_back(ConvToStr(memb->chan->age));
495                 params.push_raw(" +").push_raw(memb->chan->ChanModes(true));
496                 params.push(memb->modes).push_raw(',').push_raw(memb->user->uuid);
497                 params.Broadcast();
498         }
499         else
500         {
501                 CmdBuilder params(memb->user, "IJOIN");
502                 params.push_back(memb->chan->name);
503                 if (!memb->modes.empty())
504                 {
505                         params.push_back(ConvToStr(memb->chan->age));
506                         params.push_back(memb->modes);
507                 }
508                 params.Broadcast();
509         }
510 }
511
512 void ModuleSpanningTree::OnChangeHost(User* user, const std::string &newhost)
513 {
514         if (user->registered != REG_ALL || !IS_LOCAL(user))
515                 return;
516
517         CmdBuilder(user, "FHOST").push(newhost).Broadcast();
518 }
519
520 void ModuleSpanningTree::OnChangeName(User* user, const std::string &gecos)
521 {
522         if (user->registered != REG_ALL || !IS_LOCAL(user))
523                 return;
524
525         CmdBuilder(user, "FNAME").push(gecos).Broadcast();
526 }
527
528 void ModuleSpanningTree::OnChangeIdent(User* user, const std::string &ident)
529 {
530         if ((user->registered != REG_ALL) || (!IS_LOCAL(user)))
531                 return;
532
533         CmdBuilder(user, "FIDENT").push(ident).Broadcast();
534 }
535
536 void ModuleSpanningTree::OnUserPart(Membership* memb, std::string &partmessage, CUList& excepts)
537 {
538         if (IS_LOCAL(memb->user))
539         {
540                 CmdBuilder params(memb->user, "PART");
541                 params.push_back(memb->chan->name);
542                 if (!partmessage.empty())
543                         params.push_last(partmessage);
544                 params.Broadcast();
545         }
546 }
547
548 void ModuleSpanningTree::OnUserQuit(User* user, const std::string &reason, const std::string &oper_message)
549 {
550         if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
551         {
552                 if (oper_message != reason)
553                         ServerInstance->PI->SendMetaData(user, "operquit", oper_message);
554
555                 CmdBuilder(user, "QUIT").push_last(reason).Broadcast();
556         }
557
558         // Regardless, We need to modify the user Counts..
559         TreeServer* SourceServer = Utils->FindServer(user->server);
560         if (SourceServer)
561         {
562                 SourceServer->UserCount--;
563         }
564 }
565
566 void ModuleSpanningTree::OnUserPostNick(User* user, const std::string &oldnick)
567 {
568         if (IS_LOCAL(user))
569         {
570                 CmdBuilder params(user, "NICK");
571                 params.push_back(user->nick);
572
573                 /** IMPORTANT: We don't update the TS if the oldnick is just a case change of the newnick!
574                  */
575                 if (irc::string(user->nick.c_str()) != assign(oldnick))
576                         user->age = ServerInstance->Time();
577
578                 params.push_back(ConvToStr(user->age));
579                 params.Broadcast();
580         }
581         else if (!loopCall && user->nick == user->uuid)
582         {
583                 CmdBuilder params("SAVE");
584                 params.push_back(user->uuid);
585                 params.push_back(ConvToStr(user->age));
586                 params.Broadcast();
587         }
588 }
589
590 void ModuleSpanningTree::OnUserKick(User* source, Membership* memb, const std::string &reason, CUList& excepts)
591 {
592         if ((!IS_LOCAL(source) || source != ServerInstance->FakeClient))
593                 return;
594
595         CmdBuilder params(source, "KICK");
596         params.push_back(memb->chan->name);
597         params.push_back(memb->user->uuid);
598         params.push_last(reason);
599         params.Broadcast();
600 }
601
602 void ModuleSpanningTree::OnPreRehash(User* user, const std::string &parameter)
603 {
604         if (loopCall)
605                 return; // Don't generate a REHASH here if we're in the middle of processing a message that generated this one
606
607         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "OnPreRehash called with param %s", parameter.c_str());
608
609         // Send out to other servers
610         if (!parameter.empty() && parameter[0] != '-')
611         {
612                 CmdBuilder params((user ? user->uuid : ServerInstance->Config->GetSID()), "REHASH");
613                 params.push_back(parameter);
614                 params.Forward(user ? Utils->BestRouteTo(user->server) : NULL);
615         }
616 }
617
618 void ModuleSpanningTree::ReadConfig(ConfigStatus& status)
619 {
620         // Re-read config stuff
621         try
622         {
623                 Utils->ReadConfiguration();
624         }
625         catch (ModuleException& e)
626         {
627                 // Refresh the IP cache anyway, so servers read before the error will be allowed to connect
628                 Utils->RefreshIPCache();
629                 // Always warn local opers with snomask +l, also warn globally (snomask +L) if the rehash was issued by a remote user
630                 std::string msg = "Error in configuration: ";
631                 msg.append(e.GetReason());
632                 ServerInstance->SNO->WriteToSnoMask('l', msg);
633                 if (status.srcuser && !IS_LOCAL(status.srcuser))
634                         ServerInstance->PI->SendSNONotice("L", msg);
635         }
636 }
637
638 void ModuleSpanningTree::OnLoadModule(Module* mod)
639 {
640         std::string data;
641         data.push_back('+');
642         data.append(mod->ModuleSourceFile);
643         Version v = mod->GetVersion();
644         if (!v.link_data.empty())
645         {
646                 data.push_back('=');
647                 data.append(v.link_data);
648         }
649         ServerInstance->PI->SendMetaData("modules", data);
650 }
651
652 void ModuleSpanningTree::OnUnloadModule(Module* mod)
653 {
654         if (!Utils)
655                 return;
656         ServerInstance->PI->SendMetaData("modules", "-" + mod->ModuleSourceFile);
657
658         // Close all connections which use an IO hook provided by this module
659         const TreeServer::ChildServers& list = Utils->TreeRoot->GetChildren();
660         for (TreeServer::ChildServers::const_iterator i = list.begin(); i != list.end(); ++i)
661         {
662                 TreeSocket* sock = (*i)->GetSocket();
663                 if (sock && sock->GetIOHook() && sock->GetIOHook()->creator == mod)
664                 {
665                         sock->SendError("SSL module unloaded");
666                         sock->Close();
667                 }
668         }
669
670         for (SpanningTreeUtilities::TimeoutList::const_iterator i = Utils->timeoutlist.begin(); i != Utils->timeoutlist.end(); ++i)
671         {
672                 TreeSocket* sock = i->first;
673                 if (sock->GetIOHook() && sock->GetIOHook()->creator == mod)
674                         sock->Close();
675         }
676 }
677
678 // note: the protocol does not allow direct umode +o except
679 // via NICK with 8 params. sending OPERTYPE infers +o modechange
680 // locally.
681 void ModuleSpanningTree::OnOper(User* user, const std::string &opertype)
682 {
683         if (user->registered != REG_ALL || !IS_LOCAL(user))
684                 return;
685         CommandOpertype::Builder(user).Broadcast();
686 }
687
688 void ModuleSpanningTree::OnAddLine(User* user, XLine *x)
689 {
690         if (!x->IsBurstable() || loopCall || (user && !IS_LOCAL(user)))
691                 return;
692
693         if (!user)
694                 user = ServerInstance->FakeClient;
695
696         CommandAddLine::Builder(x, user).Broadcast();
697 }
698
699 void ModuleSpanningTree::OnDelLine(User* user, XLine *x)
700 {
701         if (!x->IsBurstable() || loopCall || (user && !IS_LOCAL(user)))
702                 return;
703
704         if (!user)
705                 user = ServerInstance->FakeClient;
706
707         CmdBuilder params(user, "DELLINE");
708         params.push_back(x->type);
709         params.push_back(x->Displayable());
710         params.Broadcast();
711 }
712
713 ModResult ModuleSpanningTree::OnSetAway(User* user, const std::string &awaymsg)
714 {
715         if (IS_LOCAL(user))
716                 CommandAway::Builder(user, awaymsg).Broadcast();
717
718         return MOD_RES_PASSTHRU;
719 }
720
721 CullResult ModuleSpanningTree::cull()
722 {
723         if (Utils)
724                 Utils->cull();
725         return this->Module::cull();
726 }
727
728 ModuleSpanningTree::~ModuleSpanningTree()
729 {
730         delete ServerInstance->PI;
731         ServerInstance->PI = new ProtocolInterface;
732
733         /* This will also free the listeners */
734         delete Utils;
735
736         delete commands;
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 return 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)