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