]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/main.cpp
7bbe5fbad02850dacfbe207bf4d1812fc18802d4
[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),
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 {
49 }
50
51 void ModuleSpanningTree::init()
52 {
53         ServerInstance->SNO->EnableSnomask('l', "LINK");
54
55         Utils = new SpanningTreeUtilities(this);
56         Utils->TreeRoot = new TreeServer;
57         commands = new SpanningTreeCommands(this);
58         ServerInstance->Modules->AddService(commands->rconnect);
59         ServerInstance->Modules->AddService(commands->rsquit);
60         ServerInstance->Modules->AddService(commands->svsjoin);
61         ServerInstance->Modules->AddService(commands->svspart);
62         ServerInstance->Modules->AddService(commands->svsnick);
63         ServerInstance->Modules->AddService(commands->metadata);
64         ServerInstance->Modules->AddService(commands->uid);
65         ServerInstance->Modules->AddService(commands->opertype);
66         ServerInstance->Modules->AddService(commands->fjoin);
67         ServerInstance->Modules->AddService(commands->ijoin);
68         ServerInstance->Modules->AddService(commands->resync);
69         ServerInstance->Modules->AddService(commands->fmode);
70         ServerInstance->Modules->AddService(commands->ftopic);
71         ServerInstance->Modules->AddService(commands->fhost);
72         ServerInstance->Modules->AddService(commands->fident);
73         ServerInstance->Modules->AddService(commands->fname);
74
75         delete ServerInstance->PI;
76         ServerInstance->PI = new SpanningTreeProtocolInterface(Utils);
77         loopCall = false;
78
79         // update our local user count
80         Utils->TreeRoot->UserCount = ServerInstance->Users->local_users.size();
81 }
82
83 void ModuleSpanningTree::ShowLinks(TreeServer* Current, User* user, int hops)
84 {
85         std::string Parent = Utils->TreeRoot->GetName();
86         if (Current->GetParent())
87         {
88                 Parent = Current->GetParent()->GetName();
89         }
90         for (unsigned int q = 0; q < Current->ChildCount(); q++)
91         {
92                 if ((Current->GetChild(q)->Hidden) || ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName()))))
93                 {
94                         if (user->IsOper())
95                         {
96                                  ShowLinks(Current->GetChild(q),user,hops+1);
97                         }
98                 }
99                 else
100                 {
101                         ShowLinks(Current->GetChild(q),user,hops+1);
102                 }
103         }
104         /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
105         if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetName())) && (!user->IsOper()))
106                 return;
107         /* Or if the server is hidden and they're not an oper */
108         else if ((Current->Hidden) && (!user->IsOper()))
109                 return;
110
111         user->WriteNumeric(364, "%s %s %s :%d %s",      user->nick.c_str(), Current->GetName().c_str(),
112                         (Utils->FlatLinks && (!user->IsOper())) ? ServerInstance->Config->ServerName.c_str() : Parent.c_str(),
113                         (Utils->FlatLinks && (!user->IsOper())) ? 0 : hops,
114                         Current->GetDesc().c_str());
115 }
116
117 int ModuleSpanningTree::CountServs()
118 {
119         return Utils->serverlist.size();
120 }
121
122 void ModuleSpanningTree::HandleLinks(const std::vector<std::string>& parameters, User* user)
123 {
124         ShowLinks(Utils->TreeRoot,user,0);
125         user->WriteNumeric(365, "%s * :End of /LINKS list.",user->nick.c_str());
126         return;
127 }
128
129 std::string ModuleSpanningTree::TimeToStr(time_t secs)
130 {
131         time_t mins_up = secs / 60;
132         time_t hours_up = mins_up / 60;
133         time_t days_up = hours_up / 24;
134         secs = secs % 60;
135         mins_up = mins_up % 60;
136         hours_up = hours_up % 24;
137         return ((days_up ? (ConvToStr(days_up) + "d") : "")
138                         + (hours_up ? (ConvToStr(hours_up) + "h") : "")
139                         + (mins_up ? (ConvToStr(mins_up) + "m") : "")
140                         + ConvToStr(secs) + "s");
141 }
142
143 void ModuleSpanningTree::DoPingChecks(time_t curtime)
144 {
145         /*
146          * Cancel remote burst mode on any servers which still have it enabled due to latency/lack of data.
147          * This prevents lost REMOTECONNECT notices
148          */
149         long ts = ServerInstance->Time() * 1000 + (ServerInstance->Time_ns() / 1000000);
150
151 restart:
152         for (server_hash::iterator i = Utils->serverlist.begin(); i != Utils->serverlist.end(); i++)
153         {
154                 TreeServer *s = i->second;
155
156                 if (s->GetSocket() && s->GetSocket()->GetLinkState() == DYING)
157                 {
158                         s->GetSocket()->Close();
159                         goto restart;
160                 }
161
162                 // Fix for bug #792, do not ping servers that are not connected yet!
163                 // Remote servers have Socket == NULL and local connected servers have
164                 // Socket->LinkState == CONNECTED
165                 if (s->GetSocket() && s->GetSocket()->GetLinkState() != CONNECTED)
166                         continue;
167
168                 // Now do PING checks on all servers
169                 TreeServer *mts = Utils->BestRouteTo(s->GetID());
170
171                 if (mts)
172                 {
173                         // Only ping if this server needs one
174                         if (curtime >= s->NextPingTime())
175                         {
176                                 // And if they answered the last
177                                 if (s->AnsweredLastPing())
178                                 {
179                                         // They did, send a ping to them
180                                         s->SetNextPingTime(curtime + Utils->PingFreq);
181                                         TreeSocket *tsock = mts->GetSocket();
182
183                                         // ... if we can find a proper route to them
184                                         if (tsock)
185                                         {
186                                                 tsock->WriteLine(":" + ServerInstance->Config->GetSID() + " PING " + s->GetID());
187                                                 s->LastPingMsec = ts;
188                                         }
189                                 }
190                                 else
191                                 {
192                                         // They didn't answer the last ping, if they are locally connected, get rid of them.
193                                         TreeSocket *sock = s->GetSocket();
194                                         if (sock)
195                                         {
196                                                 sock->SendError("Ping timeout");
197                                                 sock->Close();
198                                                 goto restart;
199                                         }
200                                 }
201                         }
202
203                         // If warn on ping enabled and not warned and the difference is sufficient and they didn't answer the last ping...
204                         if ((Utils->PingWarnTime) && (!s->Warned) && (curtime >= s->NextPingTime() - (Utils->PingFreq - Utils->PingWarnTime)) && (!s->AnsweredLastPing()))
205                         {
206                                 /* The server hasnt responded, send a warning to opers */
207                                 ServerInstance->SNO->WriteToSnoMask('l',"Server \002%s\002 has not responded to PING for %d seconds, high latency.", s->GetName().c_str(), Utils->PingWarnTime);
208                                 s->Warned = true;
209                         }
210                 }
211         }
212 }
213
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)))
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());
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                 std::string Version = found->GetVersion();
359                 user->WriteNumeric(351, "%s :%s",user->nick.c_str(),Version.c_str());
360         }
361         else
362         {
363                 user->WriteNumeric(402, "%s %s :No such server",user->nick.c_str(),parameters[0].c_str());
364         }
365         return MOD_RES_DENY;
366 }
367
368 /* This method will attempt to get a message to a remote user.
369  */
370 void ModuleSpanningTree::RemoteMessage(User* user, const char* format, ...)
371 {
372         std::string text;
373         VAFORMAT(text, format, format);
374
375         if (IS_LOCAL(user))
376                 user->WriteNotice(text);
377         else
378                 ServerInstance->PI->SendUserNotice(user, text);
379 }
380
381 ModResult ModuleSpanningTree::HandleConnect(const std::vector<std::string>& parameters, User* user)
382 {
383         for (std::vector<reference<Link> >::iterator i = Utils->LinkBlocks.begin(); i < Utils->LinkBlocks.end(); i++)
384         {
385                 Link* x = *i;
386                 if (InspIRCd::Match(x->Name.c_str(),parameters[0]))
387                 {
388                         if (InspIRCd::Match(ServerInstance->Config->ServerName, assign(x->Name)))
389                         {
390                                 RemoteMessage(user, "*** CONNECT: Server \002%s\002 is ME, not connecting.",x->Name.c_str());
391                                 return MOD_RES_DENY;
392                         }
393
394                         TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
395                         if (!CheckDupe)
396                         {
397                                 RemoteMessage(user, "*** CONNECT: Connecting to server: \002%s\002 (%s:%d)",x->Name.c_str(),(x->HiddenFromStats ? "<hidden>" : x->IPAddr.c_str()),x->Port);
398                                 ConnectServer(x);
399                                 return MOD_RES_DENY;
400                         }
401                         else
402                         {
403                                 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());
404                                 return MOD_RES_DENY;
405                         }
406                 }
407         }
408         RemoteMessage(user, "*** CONNECT: No server matching \002%s\002 could be found in the config file.",parameters[0].c_str());
409         return MOD_RES_DENY;
410 }
411
412 void ModuleSpanningTree::OnGetServerDescription(const std::string &servername,std::string &description)
413 {
414         TreeServer* s = Utils->FindServer(servername);
415         if (s)
416         {
417                 description = s->GetDesc();
418         }
419 }
420
421 void ModuleSpanningTree::OnUserInvite(User* source,User* dest,Channel* channel, time_t expiry)
422 {
423         if (IS_LOCAL(source))
424         {
425                 parameterlist params;
426                 params.push_back(dest->uuid);
427                 params.push_back(channel->name);
428                 params.push_back(ConvToStr(expiry));
429                 Utils->DoOneToMany(source->uuid,"INVITE",params);
430         }
431 }
432
433 void ModuleSpanningTree::OnPostTopicChange(User* user, Channel* chan, const std::string &topic)
434 {
435         // Drop remote events on the floor.
436         if (!IS_LOCAL(user))
437                 return;
438
439         parameterlist params;
440         params.push_back(chan->name);
441         params.push_back(":"+topic);
442         Utils->DoOneToMany(user->uuid,"TOPIC",params);
443 }
444
445 void ModuleSpanningTree::LocalMessage(User* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list, const char* message_type)
446 {
447         /* Server or remote origin, dest should always be non-null */
448         if ((!user) || (!IS_LOCAL(user)) || (!dest))
449                 return;
450
451         if (target_type == TYPE_USER)
452         {
453                 User* d = (User*) dest;
454                 if (!IS_LOCAL(d))
455                 {
456                         parameterlist params;
457                         params.push_back(d->uuid);
458                         params.push_back(":"+text);
459                         Utils->DoOneToOne(user->uuid, message_type, params, d->server);
460                 }
461         }
462         else if (target_type == TYPE_CHANNEL)
463         {
464                 Utils->SendChannelMessage(user->uuid, (Channel*)dest, text, status, exempt_list, message_type);
465         }
466         else if (target_type == TYPE_SERVER)
467         {
468                 char* target = (char*) dest;
469                 parameterlist par;
470                 par.push_back(target);
471                 par.push_back(":"+text);
472                 Utils->DoOneToMany(user->uuid, message_type, par);
473         }
474 }
475
476 void ModuleSpanningTree::OnUserMessage(User* user, void* dest, int target_type, const std::string& text, char status, const CUList& exempt_list, MessageType msgtype)
477 {
478         LocalMessage(user, dest, target_type, text, status, exempt_list, (msgtype == MSG_PRIVMSG ? "PRIVMSG" : "NOTICE"));
479 }
480
481 void ModuleSpanningTree::OnBackgroundTimer(time_t curtime)
482 {
483         AutoConnectServers(curtime);
484         DoPingChecks(curtime);
485         DoConnectTimeout(curtime);
486 }
487
488 void ModuleSpanningTree::OnUserConnect(LocalUser* user)
489 {
490         if (user->quitting)
491                 return;
492
493         parameterlist params;
494         params.push_back(user->uuid);
495         params.push_back(ConvToStr(user->age));
496         params.push_back(user->nick);
497         params.push_back(user->host);
498         params.push_back(user->dhost);
499         params.push_back(user->ident);
500         params.push_back(user->GetIPString());
501         params.push_back(ConvToStr(user->signon));
502         params.push_back("+"+std::string(user->FormatModes(true)));
503         params.push_back(":"+user->fullname);
504         Utils->DoOneToMany(ServerInstance->Config->GetSID(), "UID", params);
505
506         if (user->IsOper())
507         {
508                 params.clear();
509                 params.push_back(":");
510                 params[0].append(user->oper->name);
511                 Utils->DoOneToMany(user->uuid,"OPERTYPE",params);
512         }
513
514         for(Extensible::ExtensibleStore::const_iterator i = user->GetExtList().begin(); i != user->GetExtList().end(); i++)
515         {
516                 ExtensionItem* item = i->first;
517                 std::string value = item->serialize(FORMAT_NETWORK, user, i->second);
518                 if (!value.empty())
519                         ServerInstance->PI->SendMetaData(user, item->name, value);
520         }
521
522         Utils->TreeRoot->UserCount++;
523 }
524
525 void ModuleSpanningTree::OnUserJoin(Membership* memb, bool sync, bool created_by_local, CUList& excepts)
526 {
527         // Only do this for local users
528         if (IS_LOCAL(memb->user))
529         {
530                 parameterlist params;
531                 params.push_back(memb->chan->name);
532                 if (created_by_local)
533                 {
534                         params.push_back(ConvToStr(memb->chan->age));
535                         params.push_back(std::string("+") + memb->chan->ChanModes(true));
536                         params.push_back(memb->modes+","+memb->user->uuid);
537                         Utils->DoOneToMany(ServerInstance->Config->GetSID(),"FJOIN",params);
538                 }
539                 else
540                 {
541                         if (!memb->modes.empty())
542                         {
543                                 params.push_back(ConvToStr(memb->chan->age));
544                                 params.push_back(memb->modes);
545                         }
546                         Utils->DoOneToMany(memb->user->uuid, "IJOIN", params);
547                 }
548         }
549 }
550
551 void ModuleSpanningTree::OnChangeHost(User* user, const std::string &newhost)
552 {
553         if (user->registered != REG_ALL || !IS_LOCAL(user))
554                 return;
555
556         parameterlist params;
557         params.push_back(newhost);
558         Utils->DoOneToMany(user->uuid,"FHOST",params);
559 }
560
561 void ModuleSpanningTree::OnChangeName(User* user, const std::string &gecos)
562 {
563         if (user->registered != REG_ALL || !IS_LOCAL(user))
564                 return;
565
566         parameterlist params;
567         params.push_back(gecos);
568         Utils->DoOneToMany(user->uuid,"FNAME",params);
569 }
570
571 void ModuleSpanningTree::OnChangeIdent(User* user, const std::string &ident)
572 {
573         if ((user->registered != REG_ALL) || (!IS_LOCAL(user)))
574                 return;
575
576         parameterlist params;
577         params.push_back(ident);
578         Utils->DoOneToMany(user->uuid,"FIDENT",params);
579 }
580
581 void ModuleSpanningTree::OnUserPart(Membership* memb, std::string &partmessage, CUList& excepts)
582 {
583         if (IS_LOCAL(memb->user))
584         {
585                 parameterlist params;
586                 params.push_back(memb->chan->name);
587                 if (!partmessage.empty())
588                         params.push_back(":"+partmessage);
589                 Utils->DoOneToMany(memb->user->uuid,"PART",params);
590         }
591 }
592
593 void ModuleSpanningTree::OnUserQuit(User* user, const std::string &reason, const std::string &oper_message)
594 {
595         if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
596         {
597                 parameterlist params;
598
599                 if (oper_message != reason)
600                         ServerInstance->PI->SendMetaData(user, "operquit", oper_message);
601
602                 params.push_back(":"+reason);
603                 Utils->DoOneToMany(user->uuid,"QUIT",params);
604         }
605
606         // Regardless, We need to modify the user Counts..
607         TreeServer* SourceServer = Utils->FindServer(user->server);
608         if (SourceServer)
609         {
610                 SourceServer->UserCount--;
611         }
612 }
613
614 void ModuleSpanningTree::OnUserPostNick(User* user, const std::string &oldnick)
615 {
616         if (IS_LOCAL(user))
617         {
618                 parameterlist params;
619                 params.push_back(user->nick);
620
621                 /** IMPORTANT: We don't update the TS if the oldnick is just a case change of the newnick!
622                  */
623                 if (irc::string(user->nick.c_str()) != assign(oldnick))
624                         user->age = ServerInstance->Time();
625
626                 params.push_back(ConvToStr(user->age));
627                 Utils->DoOneToMany(user->uuid,"NICK",params);
628         }
629         else if (!loopCall && user->nick == user->uuid)
630         {
631                 parameterlist params;
632                 params.push_back(user->uuid);
633                 params.push_back(ConvToStr(user->age));
634                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"SAVE",params);
635         }
636 }
637
638 void ModuleSpanningTree::OnUserKick(User* source, Membership* memb, const std::string &reason, CUList& excepts)
639 {
640         parameterlist params;
641         params.push_back(memb->chan->name);
642         params.push_back(memb->user->uuid);
643         params.push_back(":"+reason);
644         if (IS_LOCAL(source))
645         {
646                 Utils->DoOneToMany(source->uuid,"KICK",params);
647         }
648         else if (source == ServerInstance->FakeClient)
649         {
650                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"KICK",params);
651         }
652 }
653
654 void ModuleSpanningTree::OnPreRehash(User* user, const std::string &parameter)
655 {
656         if (loopCall)
657                 return; // Don't generate a REHASH here if we're in the middle of processing a message that generated this one
658
659         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "OnPreRehash called with param %s", parameter.c_str());
660
661         // Send out to other servers
662         if (!parameter.empty() && parameter[0] != '-')
663         {
664                 parameterlist params;
665                 params.push_back(parameter);
666                 Utils->DoOneToAllButSender(user ? user->uuid : ServerInstance->Config->GetSID(), "REHASH", params, user ? user->server : ServerInstance->Config->ServerName);
667         }
668 }
669
670 void ModuleSpanningTree::OnRehash(User* user)
671 {
672         // Re-read config stuff
673         try
674         {
675                 Utils->ReadConfiguration();
676         }
677         catch (ModuleException& e)
678         {
679                 // Refresh the IP cache anyway, so servers read before the error will be allowed to connect
680                 Utils->RefreshIPCache();
681                 // Always warn local opers with snomask +l, also warn globally (snomask +L) if the rehash was issued by a remote user
682                 std::string msg = "Error in configuration: ";
683                 msg.append(e.GetReason());
684                 ServerInstance->SNO->WriteToSnoMask('l', msg);
685                 if (user && !IS_LOCAL(user))
686                         ServerInstance->PI->SendSNONotice("L", msg);
687         }
688 }
689
690 void ModuleSpanningTree::OnLoadModule(Module* mod)
691 {
692         std::string data;
693         data.push_back('+');
694         data.append(mod->ModuleSourceFile);
695         Version v = mod->GetVersion();
696         if (!v.link_data.empty())
697         {
698                 data.push_back('=');
699                 data.append(v.link_data);
700         }
701         ServerInstance->PI->SendMetaData(NULL, "modules", data);
702 }
703
704 void ModuleSpanningTree::OnUnloadModule(Module* mod)
705 {
706         ServerInstance->PI->SendMetaData(NULL, "modules", "-" + mod->ModuleSourceFile);
707
708         unsigned int items = Utils->TreeRoot->ChildCount();
709         for(unsigned int x = 0; x < items; x++)
710         {
711                 TreeServer* srv = Utils->TreeRoot->GetChild(x);
712                 TreeSocket* sock = srv->GetSocket();
713                 if (sock && sock->GetIOHook() && sock->GetIOHook()->creator == mod)
714                 {
715                         sock->SendError("SSL module unloaded");
716                         sock->Close();
717                 }
718         }
719 }
720
721 // note: the protocol does not allow direct umode +o except
722 // via NICK with 8 params. sending OPERTYPE infers +o modechange
723 // locally.
724 void ModuleSpanningTree::OnOper(User* user, const std::string &opertype)
725 {
726         if (user->registered != REG_ALL || !IS_LOCAL(user))
727                 return;
728         parameterlist params;
729         params.push_back(":");
730         params[0].append(opertype);
731         Utils->DoOneToMany(user->uuid,"OPERTYPE",params);
732 }
733
734 void ModuleSpanningTree::OnAddLine(User* user, XLine *x)
735 {
736         if (!x->IsBurstable() || loopCall)
737                 return;
738
739         parameterlist params;
740         params.push_back(x->type);
741         params.push_back(x->Displayable());
742         params.push_back(ServerInstance->Config->ServerName);
743         params.push_back(ConvToStr(x->set_time));
744         params.push_back(ConvToStr(x->duration));
745         params.push_back(":" + x->reason);
746
747         if (!user)
748         {
749                 /* Server-set lines */
750                 Utils->DoOneToMany(ServerInstance->Config->GetSID(), "ADDLINE", params);
751         }
752         else if (IS_LOCAL(user))
753         {
754                 /* User-set lines */
755                 Utils->DoOneToMany(user->uuid, "ADDLINE", params);
756         }
757 }
758
759 void ModuleSpanningTree::OnDelLine(User* user, XLine *x)
760 {
761         if (!x->IsBurstable() || loopCall)
762                 return;
763
764         parameterlist params;
765         params.push_back(x->type);
766         params.push_back(x->Displayable());
767
768         if (!user)
769         {
770                 /* Server-unset lines */
771                 Utils->DoOneToMany(ServerInstance->Config->GetSID(), "DELLINE", params);
772         }
773         else if (IS_LOCAL(user))
774         {
775                 /* User-unset lines */
776                 Utils->DoOneToMany(user->uuid, "DELLINE", params);
777         }
778 }
779
780 ModResult ModuleSpanningTree::OnSetAway(User* user, const std::string &awaymsg)
781 {
782         if (IS_LOCAL(user))
783         {
784                 parameterlist params;
785                 if (!awaymsg.empty())
786                 {
787                         params.push_back(ConvToStr(user->awaytime));
788                         params.push_back(":" + awaymsg);
789                 }
790                 Utils->DoOneToMany(user->uuid, "AWAY", params);
791         }
792
793         return MOD_RES_PASSTHRU;
794 }
795
796 void ModuleSpanningTree::ProtoSendMode(void* opaque, TargetTypeFlags target_type, void* target, const parameterlist &modeline, const std::vector<TranslateType> &translate)
797 {
798         TreeSocket* s = (TreeSocket*)opaque;
799         std::string output_text = CommandParser::TranslateUIDs(translate, modeline);
800
801         if (target)
802         {
803                 if (target_type == TYPE_USER)
804                 {
805                         User* u = (User*)target;
806                         s->WriteLine(":"+ServerInstance->Config->GetSID()+" MODE "+u->uuid+" "+output_text);
807                 }
808                 else if (target_type == TYPE_CHANNEL)
809                 {
810                         Channel* c = (Channel*)target;
811                         s->WriteLine(":"+ServerInstance->Config->GetSID()+" FMODE "+c->name+" "+ConvToStr(c->age)+" "+output_text);
812                 }
813         }
814 }
815
816 void ModuleSpanningTree::ProtoSendMetaData(void* opaque, Extensible* target, const std::string &extname, const std::string &extdata)
817 {
818         TreeSocket* s = static_cast<TreeSocket*>(opaque);
819         User* u = dynamic_cast<User*>(target);
820         Channel* c = dynamic_cast<Channel*>(target);
821         if (u)
822                 s->WriteLine(":"+ServerInstance->Config->GetSID()+" METADATA "+u->uuid+" "+extname+" :"+extdata);
823         else if (c)
824                 s->WriteLine(":"+ServerInstance->Config->GetSID()+" METADATA "+c->name+" "+ConvToStr(c->age)+" "+extname+" :"+extdata);
825         else if (!target)
826                 s->WriteLine(":"+ServerInstance->Config->GetSID()+" METADATA * "+extname+" :"+extdata);
827 }
828
829 CullResult ModuleSpanningTree::cull()
830 {
831         if (Utils)
832                 Utils->cull();
833         return this->Module::cull();
834 }
835
836 ModuleSpanningTree::~ModuleSpanningTree()
837 {
838         delete ServerInstance->PI;
839         ServerInstance->PI = new ProtocolInterface;
840
841         /* This will also free the listeners */
842         delete Utils;
843
844         delete commands;
845 }
846
847 Version ModuleSpanningTree::GetVersion()
848 {
849         return Version("Allows servers to be linked", VF_VENDOR);
850 }
851
852 /* It is IMPORTANT that m_spanningtree is the last module in the chain
853  * so that any activity it sees is FINAL, e.g. we arent going to send out
854  * a NICK message before m_cloaking has finished putting the +x on the user,
855  * etc etc.
856  * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
857  * the module call queue.
858  */
859 void ModuleSpanningTree::Prioritize()
860 {
861         ServerInstance->Modules->SetPriority(this, PRIORITY_LAST);
862 }
863
864 MODULE_INIT(ModuleSpanningTree)