]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/main.cpp
m_spanningtree Remove SpanningTreeUtilities* fields and parameters
[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                 {
601                         params.push_back(":"+oper_message);
602                         Utils->DoOneToMany(user->uuid,"OPERQUIT",params);
603                 }
604                 params.clear();
605                 params.push_back(":"+reason);
606                 Utils->DoOneToMany(user->uuid,"QUIT",params);
607         }
608
609         // Regardless, We need to modify the user Counts..
610         TreeServer* SourceServer = Utils->FindServer(user->server);
611         if (SourceServer)
612         {
613                 SourceServer->UserCount--;
614         }
615 }
616
617 void ModuleSpanningTree::OnUserPostNick(User* user, const std::string &oldnick)
618 {
619         if (IS_LOCAL(user))
620         {
621                 parameterlist params;
622                 params.push_back(user->nick);
623
624                 /** IMPORTANT: We don't update the TS if the oldnick is just a case change of the newnick!
625                  */
626                 if (irc::string(user->nick.c_str()) != assign(oldnick))
627                         user->age = ServerInstance->Time();
628
629                 params.push_back(ConvToStr(user->age));
630                 Utils->DoOneToMany(user->uuid,"NICK",params);
631         }
632         else if (!loopCall && user->nick == user->uuid)
633         {
634                 parameterlist params;
635                 params.push_back(user->uuid);
636                 params.push_back(ConvToStr(user->age));
637                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"SAVE",params);
638         }
639 }
640
641 void ModuleSpanningTree::OnUserKick(User* source, Membership* memb, const std::string &reason, CUList& excepts)
642 {
643         parameterlist params;
644         params.push_back(memb->chan->name);
645         params.push_back(memb->user->uuid);
646         params.push_back(":"+reason);
647         if (IS_LOCAL(source))
648         {
649                 Utils->DoOneToMany(source->uuid,"KICK",params);
650         }
651         else if (source == ServerInstance->FakeClient)
652         {
653                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"KICK",params);
654         }
655 }
656
657 void ModuleSpanningTree::OnPreRehash(User* user, const std::string &parameter)
658 {
659         if (loopCall)
660                 return; // Don't generate a REHASH here if we're in the middle of processing a message that generated this one
661
662         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "OnPreRehash called with param %s", parameter.c_str());
663
664         // Send out to other servers
665         if (!parameter.empty() && parameter[0] != '-')
666         {
667                 parameterlist params;
668                 params.push_back(parameter);
669                 Utils->DoOneToAllButSender(user ? user->uuid : ServerInstance->Config->GetSID(), "REHASH", params, user ? user->server : ServerInstance->Config->ServerName);
670         }
671 }
672
673 void ModuleSpanningTree::OnRehash(User* user)
674 {
675         // Re-read config stuff
676         try
677         {
678                 Utils->ReadConfiguration();
679         }
680         catch (ModuleException& e)
681         {
682                 // Refresh the IP cache anyway, so servers read before the error will be allowed to connect
683                 Utils->RefreshIPCache();
684                 // Always warn local opers with snomask +l, also warn globally (snomask +L) if the rehash was issued by a remote user
685                 std::string msg = "Error in configuration: ";
686                 msg.append(e.GetReason());
687                 ServerInstance->SNO->WriteToSnoMask('l', msg);
688                 if (user && !IS_LOCAL(user))
689                         ServerInstance->PI->SendSNONotice("L", msg);
690         }
691 }
692
693 void ModuleSpanningTree::OnLoadModule(Module* mod)
694 {
695         std::string data;
696         data.push_back('+');
697         data.append(mod->ModuleSourceFile);
698         Version v = mod->GetVersion();
699         if (!v.link_data.empty())
700         {
701                 data.push_back('=');
702                 data.append(v.link_data);
703         }
704         ServerInstance->PI->SendMetaData(NULL, "modules", data);
705 }
706
707 void ModuleSpanningTree::OnUnloadModule(Module* mod)
708 {
709         ServerInstance->PI->SendMetaData(NULL, "modules", "-" + mod->ModuleSourceFile);
710
711         unsigned int items = Utils->TreeRoot->ChildCount();
712         for(unsigned int x = 0; x < items; x++)
713         {
714                 TreeServer* srv = Utils->TreeRoot->GetChild(x);
715                 TreeSocket* sock = srv->GetSocket();
716                 if (sock && sock->GetIOHook() && sock->GetIOHook()->creator == mod)
717                 {
718                         sock->SendError("SSL module unloaded");
719                         sock->Close();
720                 }
721         }
722 }
723
724 // note: the protocol does not allow direct umode +o except
725 // via NICK with 8 params. sending OPERTYPE infers +o modechange
726 // locally.
727 void ModuleSpanningTree::OnOper(User* user, const std::string &opertype)
728 {
729         if (user->registered != REG_ALL || !IS_LOCAL(user))
730                 return;
731         parameterlist params;
732         params.push_back(":");
733         params[0].append(opertype);
734         Utils->DoOneToMany(user->uuid,"OPERTYPE",params);
735 }
736
737 void ModuleSpanningTree::OnAddLine(User* user, XLine *x)
738 {
739         if (!x->IsBurstable() || loopCall)
740                 return;
741
742         parameterlist params;
743         params.push_back(x->type);
744         params.push_back(x->Displayable());
745         params.push_back(ServerInstance->Config->ServerName);
746         params.push_back(ConvToStr(x->set_time));
747         params.push_back(ConvToStr(x->duration));
748         params.push_back(":" + x->reason);
749
750         if (!user)
751         {
752                 /* Server-set lines */
753                 Utils->DoOneToMany(ServerInstance->Config->GetSID(), "ADDLINE", params);
754         }
755         else if (IS_LOCAL(user))
756         {
757                 /* User-set lines */
758                 Utils->DoOneToMany(user->uuid, "ADDLINE", params);
759         }
760 }
761
762 void ModuleSpanningTree::OnDelLine(User* user, XLine *x)
763 {
764         if (!x->IsBurstable() || loopCall)
765                 return;
766
767         parameterlist params;
768         params.push_back(x->type);
769         params.push_back(x->Displayable());
770
771         if (!user)
772         {
773                 /* Server-unset lines */
774                 Utils->DoOneToMany(ServerInstance->Config->GetSID(), "DELLINE", params);
775         }
776         else if (IS_LOCAL(user))
777         {
778                 /* User-unset lines */
779                 Utils->DoOneToMany(user->uuid, "DELLINE", params);
780         }
781 }
782
783 ModResult ModuleSpanningTree::OnSetAway(User* user, const std::string &awaymsg)
784 {
785         if (IS_LOCAL(user))
786         {
787                 parameterlist params;
788                 if (!awaymsg.empty())
789                 {
790                         params.push_back(ConvToStr(user->awaytime));
791                         params.push_back(":" + awaymsg);
792                 }
793                 Utils->DoOneToMany(user->uuid, "AWAY", params);
794         }
795
796         return MOD_RES_PASSTHRU;
797 }
798
799 void ModuleSpanningTree::ProtoSendMode(void* opaque, TargetTypeFlags target_type, void* target, const parameterlist &modeline, const std::vector<TranslateType> &translate)
800 {
801         TreeSocket* s = (TreeSocket*)opaque;
802         std::string output_text = CommandParser::TranslateUIDs(translate, modeline);
803
804         if (target)
805         {
806                 if (target_type == TYPE_USER)
807                 {
808                         User* u = (User*)target;
809                         s->WriteLine(":"+ServerInstance->Config->GetSID()+" MODE "+u->uuid+" "+output_text);
810                 }
811                 else if (target_type == TYPE_CHANNEL)
812                 {
813                         Channel* c = (Channel*)target;
814                         s->WriteLine(":"+ServerInstance->Config->GetSID()+" FMODE "+c->name+" "+ConvToStr(c->age)+" "+output_text);
815                 }
816         }
817 }
818
819 void ModuleSpanningTree::ProtoSendMetaData(void* opaque, Extensible* target, const std::string &extname, const std::string &extdata)
820 {
821         TreeSocket* s = static_cast<TreeSocket*>(opaque);
822         User* u = dynamic_cast<User*>(target);
823         Channel* c = dynamic_cast<Channel*>(target);
824         if (u)
825                 s->WriteLine(":"+ServerInstance->Config->GetSID()+" METADATA "+u->uuid+" "+extname+" :"+extdata);
826         else if (c)
827                 s->WriteLine(":"+ServerInstance->Config->GetSID()+" METADATA "+c->name+" "+ConvToStr(c->age)+" "+extname+" :"+extdata);
828         else if (!target)
829                 s->WriteLine(":"+ServerInstance->Config->GetSID()+" METADATA * "+extname+" :"+extdata);
830 }
831
832 CullResult ModuleSpanningTree::cull()
833 {
834         if (Utils)
835                 Utils->cull();
836         return this->Module::cull();
837 }
838
839 ModuleSpanningTree::~ModuleSpanningTree()
840 {
841         delete ServerInstance->PI;
842         ServerInstance->PI = new ProtocolInterface;
843
844         /* This will also free the listeners */
845         delete Utils;
846
847         delete commands;
848 }
849
850 Version ModuleSpanningTree::GetVersion()
851 {
852         return Version("Allows servers to be linked", VF_VENDOR);
853 }
854
855 /* It is IMPORTANT that m_spanningtree is the last module in the chain
856  * so that any activity it sees is FINAL, e.g. we arent going to send out
857  * a NICK message before m_cloaking has finished putting the +x on the user,
858  * etc etc.
859  * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
860  * the module call queue.
861  */
862 void ModuleSpanningTree::Prioritize()
863 {
864         ServerInstance->Modules->SetPriority(this, PRIORITY_LAST);
865 }
866
867 MODULE_INIT(ModuleSpanningTree)