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