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