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