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