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