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