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