]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/main.cpp
Fix ping server-skip logic from bug 792 fix
[user/henk/code/inspircd.git] / src / modules / m_spanningtree / main.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2009 InspIRCd Development Team
6  * See: http://wiki.inspircd.org/Credits
7  *
8  * This program is free but copyrighted software; see
9  *          the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 /* $ModDesc: Provides a spanning tree server link protocol */
15
16 #include "inspircd.h"
17 #include "commands/cmd_whois.h"
18 #include "commands/cmd_stats.h"
19 #include "socket.h"
20 #include "xline.h"
21 #include "transport.h"
22
23 #include "m_spanningtree/cachetimer.h"
24 #include "m_spanningtree/resolvers.h"
25 #include "m_spanningtree/main.h"
26 #include "m_spanningtree/utils.h"
27 #include "m_spanningtree/treeserver.h"
28 #include "m_spanningtree/link.h"
29 #include "m_spanningtree/treesocket.h"
30 #include "m_spanningtree/rconnect.h"
31 #include "m_spanningtree/rsquit.h"
32 #include "m_spanningtree/protocolinterface.h"
33
34 /* $ModDep: m_spanningtree/cachetimer.h m_spanningtree/resolvers.h m_spanningtree/main.h m_spanningtree/utils.h m_spanningtree/treeserver.h m_spanningtree/link.h m_spanningtree/treesocket.h m_spanningtree/rconnect.h m_spanningtree/rsquit.h m_spanningtree/protocolinterface.h */
35
36 ModuleSpanningTree::ModuleSpanningTree(InspIRCd* Me)
37         : Module(Me), max_local(0), max_global(0)
38 {
39         ServerInstance->Modules->UseInterface("BufferedSocketHook");
40         Utils = new SpanningTreeUtilities(ServerInstance, this);
41         command_rconnect = new CommandRConnect(ServerInstance, this, Utils);
42         ServerInstance->AddCommand(command_rconnect);
43         command_rsquit = new CommandRSQuit(ServerInstance, this, Utils);
44         ServerInstance->AddCommand(command_rsquit);
45         RefreshTimer = new CacheRefreshTimer(ServerInstance, Utils);
46         ServerInstance->Timers->AddTimer(RefreshTimer);
47
48         Implementation eventlist[] =
49         {
50                 I_OnPreCommand, I_OnGetServerDescription, I_OnUserInvite, I_OnPostLocalTopicChange,
51                 I_OnWallops, I_OnUserNotice, I_OnUserMessage, I_OnBackgroundTimer,
52                 I_OnUserJoin, I_OnChangeLocalUserHost, I_OnChangeName, I_OnUserPart, I_OnUnloadModule,
53                 I_OnUserQuit, I_OnUserPostNick, I_OnUserKick, I_OnRemoteKill, I_OnRehash,
54                 I_OnOper, I_OnAddLine, I_OnDelLine, I_ProtoSendMode, I_OnMode, I_OnLoadModule,
55                 I_OnStats, I_ProtoSendMetaData, I_OnEvent, I_OnSetAway, I_OnPostCommand
56         };
57         ServerInstance->Modules->Attach(eventlist, this, 29);
58
59         delete ServerInstance->PI;
60         ServerInstance->PI = new SpanningTreeProtocolInterface(this, Utils, ServerInstance);
61
62         for (std::vector<User*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
63         {
64                 ServerInstance->PI->Introduce(*i);
65         }
66 }
67
68 void ModuleSpanningTree::ShowLinks(TreeServer* Current, User* user, int hops)
69 {
70         std::string Parent = Utils->TreeRoot->GetName();
71         if (Current->GetParent())
72         {
73                 Parent = Current->GetParent()->GetName();
74         }
75         for (unsigned int q = 0; q < Current->ChildCount(); q++)
76         {
77                 if ((Current->GetChild(q)->Hidden) || ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str()))))
78                 {
79                         if (IS_OPER(user))
80                         {
81                                  ShowLinks(Current->GetChild(q),user,hops+1);
82                         }
83                 }
84                 else
85                 {
86                         ShowLinks(Current->GetChild(q),user,hops+1);
87                 }
88         }
89         /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
90         if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetName().c_str())) && (!IS_OPER(user)))
91                 return;
92         /* Or if the server is hidden and they're not an oper */
93         else if ((Current->Hidden) && (!IS_OPER(user)))
94                 return;
95
96         user->WriteNumeric(364, "%s %s %s :%d %s",      user->nick.c_str(),Current->GetName().c_str(),
97                         (Utils->FlatLinks && (!IS_OPER(user))) ? ServerInstance->Config->ServerName : Parent.c_str(),
98                         (Utils->FlatLinks && (!IS_OPER(user))) ? 0 : hops,
99                         Current->GetDesc().c_str());
100 }
101
102 int ModuleSpanningTree::CountLocalServs()
103 {
104         return Utils->TreeRoot->ChildCount();
105 }
106
107 int ModuleSpanningTree::CountServs()
108 {
109         return Utils->serverlist.size();
110 }
111
112 void ModuleSpanningTree::HandleLinks(const std::vector<std::string>& parameters, User* user)
113 {
114         ShowLinks(Utils->TreeRoot,user,0);
115         user->WriteNumeric(365, "%s * :End of /LINKS list.",user->nick.c_str());
116         return;
117 }
118
119 void ModuleSpanningTree::HandleLusers(const std::vector<std::string>& parameters, User* user)
120 {
121         unsigned int n_users = ServerInstance->Users->UserCount();
122
123         /* Only update these when someone wants to see them, more efficient */
124         if ((unsigned int)ServerInstance->Users->LocalUserCount() > max_local)
125                 max_local = ServerInstance->Users->LocalUserCount();
126         if (n_users > max_global)
127                 max_global = n_users;
128
129         unsigned int ulined_count = 0;
130         unsigned int ulined_local_count = 0;
131
132         /* If ulined are hidden and we're not an oper, count the number of ulined servers hidden,
133          * locally and globally (locally means directly connected to us)
134          */
135         if ((Utils->HideULines) && (!IS_OPER(user)))
136         {
137                 for (server_hash::iterator q = Utils->serverlist.begin(); q != Utils->serverlist.end(); q++)
138                 {
139                         if (ServerInstance->ULine(q->second->GetName().c_str()))
140                         {
141                                 ulined_count++;
142                                 if (q->second->GetParent() == Utils->TreeRoot)
143                                         ulined_local_count++;
144                         }
145                 }
146         }
147         user->WriteNumeric(251, "%s :There are %d users and %d invisible on %d servers",user->nick.c_str(),
148                         n_users-ServerInstance->Users->ModeCount('i'),
149                         ServerInstance->Users->ModeCount('i'),
150                         ulined_count ? this->CountServs() - ulined_count : this->CountServs());
151
152         if (ServerInstance->Users->OperCount())
153                 user->WriteNumeric(252, "%s %d :operator(s) online",user->nick.c_str(),ServerInstance->Users->OperCount());
154
155         if (ServerInstance->Users->UnregisteredUserCount())
156                 user->WriteNumeric(253, "%s %d :unknown connections",user->nick.c_str(),ServerInstance->Users->UnregisteredUserCount());
157
158         if (ServerInstance->ChannelCount())
159                 user->WriteNumeric(254, "%s %ld :channels formed",user->nick.c_str(),ServerInstance->ChannelCount());
160
161         user->WriteNumeric(255, "%s :I have %d clients and %d servers",user->nick.c_str(),ServerInstance->Users->LocalUserCount(),ulined_local_count ? this->CountLocalServs() - ulined_local_count : this->CountLocalServs());
162         user->WriteNumeric(265, "%s :Current Local Users: %d  Max: %d",user->nick.c_str(),ServerInstance->Users->LocalUserCount(),max_local);
163         user->WriteNumeric(266, "%s :Current Global Users: %d  Max: %d",user->nick.c_str(),n_users,max_global);
164         return;
165 }
166
167 std::string ModuleSpanningTree::TimeToStr(time_t secs)
168 {
169         time_t mins_up = secs / 60;
170         time_t hours_up = mins_up / 60;
171         time_t days_up = hours_up / 24;
172         secs = secs % 60;
173         mins_up = mins_up % 60;
174         hours_up = hours_up % 24;
175         return ((days_up ? (ConvToStr(days_up) + "d") : std::string(""))
176                         + (hours_up ? (ConvToStr(hours_up) + "h") : std::string(""))
177                         + (mins_up ? (ConvToStr(mins_up) + "m") : std::string(""))
178                         + ConvToStr(secs) + "s");
179 }
180
181 void ModuleSpanningTree::DoPingChecks(time_t curtime)
182 {
183         /*
184          * Cancel remote burst mode on any servers which still have it enabled due to latency/lack of data.
185          * This prevents lost REMOTECONNECT notices
186          */
187         timeval t;
188         gettimeofday(&t, NULL);
189         long ts = (t.tv_sec * 1000) + (t.tv_usec / 1000);
190
191         for (server_hash::iterator i = Utils->serverlist.begin(); i != Utils->serverlist.end(); i++)
192         {
193                 TreeServer *s = i->second;
194
195                 // Fix for bug #792, do not ping servers that are not connected yet!
196                 // Remote servers have Socket == NULL and local connected servers have
197                 // Socket->LinkState == CONNECTED
198                 if (s->GetSocket() && s->GetSocket()->GetLinkState() != CONNECTED)
199                         continue;
200
201                 // Now do PING checks on all servers
202                 TreeServer *mts = Utils->BestRouteTo(s->GetID());
203
204                 if (mts)
205                 {
206                         // Only ping if this server needs one
207                         if (curtime >= s->NextPingTime())
208                         {
209                                 // And if they answered the last
210                                 if (s->AnsweredLastPing())
211                                 {
212                                         // They did, send a ping to them
213                                         s->SetNextPingTime(curtime + Utils->PingFreq);
214                                         TreeSocket *tsock = mts->GetSocket();
215
216                                         // ... if we can find a proper route to them
217                                         if (tsock)
218                                         {
219                                                 tsock->WriteLine(std::string(":") + ServerInstance->Config->GetSID() + " PING " +
220                                                                 ServerInstance->Config->GetSID() + " " + s->GetID());
221                                                 s->LastPingMsec = ts;
222                                         }
223                                 }
224                                 else
225                                 {
226                                         // They didn't answer the last ping, if they are locally connected, get rid of them.
227                                         TreeSocket *sock = s->GetSocket();
228                                         if (sock)
229                                         {
230                                                 sock->SendError("Ping timeout");
231                                                 sock->Squit(s,"Ping timeout");
232                                                 ServerInstance->SE->DelFd(sock);
233                                                 sock->Close();
234                                                 return;
235                                         }
236                                 }
237                         }
238
239                         // If warn on ping enabled and not warned and the difference is sufficient and they didn't answer the last ping...
240                         if ((Utils->PingWarnTime) && (!s->Warned) && (curtime >= s->NextPingTime() - (Utils->PingFreq - Utils->PingWarnTime)) && (!s->AnsweredLastPing()))
241                         {
242                                 /* The server hasnt responded, send a warning to opers */
243                                 ServerInstance->SNO->WriteToSnoMask('l',"Server \002%s\002 has not responded to PING for %d seconds, high latency.", s->GetName().c_str(), Utils->PingWarnTime);
244                                 s->Warned = true;
245                         }
246                 }
247         }
248 }
249
250 void ModuleSpanningTree::ConnectServer(Link* x)
251 {
252         bool ipvalid = true;
253
254         if (InspIRCd::Match(ServerInstance->Config->ServerName, assign(x->Name)))
255         {
256                 this->ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Not connecting to myself.");
257                 return;
258         }
259
260         QueryType start_type = DNS_QUERY_A;
261 #ifdef IPV6
262         start_type = DNS_QUERY_AAAA;
263         if (strchr(x->IPAddr.c_str(),':'))
264         {
265                 in6_addr n;
266                 if (inet_pton(AF_INET6, x->IPAddr.c_str(), &n) < 1)
267                         ipvalid = false;
268         }
269         else
270 #endif
271         {
272                 in_addr n;
273                 if (inet_aton(x->IPAddr.c_str(),&n) < 1)
274                         ipvalid = false;
275         }
276
277         /* Do we already have an IP? If so, no need to resolve it. */
278         if (ipvalid)
279         {
280                 /* Gave a hook, but it wasnt one we know */
281                 if ((!x->Hook.empty()) && (Utils->hooks.find(x->Hook.c_str()) == Utils->hooks.end()))
282                         return;
283                 TreeSocket* newsocket = new TreeSocket(Utils, ServerInstance, x->IPAddr,x->Port, x->Timeout ? x->Timeout : 10,x->Name.c_str(), x->Bind, x->Hook.empty() ? NULL : Utils->hooks[x->Hook.c_str()]);
284                 if (newsocket->GetFd() > -1)
285                 {
286                         /* Handled automatically on success */
287                 }
288                 else
289                 {
290                         this->ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
291                         if (ServerInstance->SocketCull.find(newsocket) == ServerInstance->SocketCull.end())
292                                 ServerInstance->SocketCull[newsocket] = newsocket;
293                         Utils->DoFailOver(x);
294                 }
295         }
296         else
297         {
298                 try
299                 {
300                         bool cached;
301                         ServernameResolver* snr = new ServernameResolver((Module*)this, Utils, ServerInstance,x->IPAddr, *x, cached, start_type);
302                         ServerInstance->AddResolver(snr, cached);
303                 }
304                 catch (ModuleException& e)
305                 {
306                         this->ServerInstance->SNO->WriteToSnoMask('l', "CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(), e.GetReason());
307                         Utils->DoFailOver(x);
308                 }
309         }
310 }
311
312 void ModuleSpanningTree::AutoConnectServers(time_t curtime)
313 {
314         for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
315         {
316                 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
317                 {
318                         x->NextConnectTime = curtime + x->AutoConnect;
319                         TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
320                         if (x->FailOver.length())
321                         {
322                                 TreeServer* CheckFailOver = Utils->FindServer(x->FailOver.c_str());
323                                 if (CheckFailOver)
324                                 {
325                                         /* The failover for this server is currently a member of the network.
326                                          * The failover probably succeeded, where the main link did not.
327                                          * Don't try the main link until the failover is gone again.
328                                          */
329                                         continue;
330                                 }
331                         }
332                         if (!CheckDupe)
333                         {
334                                 // an autoconnected server is not connected. Check if its time to connect it
335                                 ServerInstance->SNO->WriteToSnoMask('l',"AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
336                                 this->ConnectServer(&(*x));
337                         }
338                 }
339         }
340 }
341
342 void ModuleSpanningTree::DoConnectTimeout(time_t curtime)
343 {
344         std::vector<Link*> failovers;
345         for (std::map<TreeSocket*, std::pair<std::string, int> >::iterator i = Utils->timeoutlist.begin(); i != Utils->timeoutlist.end(); i++)
346         {
347                 TreeSocket* s = i->first;
348                 std::pair<std::string, int> p = i->second;
349                 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                         ServerInstance->SE->DelFd(s);
353                         s->Close();
354                         Link* MyLink = Utils->FindLink(p.first);
355                         if (MyLink)
356                                 failovers.push_back(MyLink);
357                 }
358         }
359         /* Trigger failover for each timed out socket */
360         for (std::vector<Link*>::const_iterator n = failovers.begin(); n != failovers.end(); ++n)
361         {
362                 Utils->DoFailOver(*n);
363         }
364 }
365
366 int ModuleSpanningTree::HandleVersion(const std::vector<std::string>& parameters, User* user)
367 {
368         // we've already checked if pcnt > 0, so this is safe
369         TreeServer* found = Utils->FindServerMask(parameters[0]);
370         if (found)
371         {
372                 std::string Version = found->GetVersion();
373                 user->WriteNumeric(351, "%s :%s",user->nick.c_str(),Version.c_str());
374                 if (found == Utils->TreeRoot)
375                 {
376                         ServerInstance->Config->Send005(user);
377                 }
378         }
379         else
380         {
381                 user->WriteNumeric(402, "%s %s :No such server",user->nick.c_str(),parameters[0].c_str());
382         }
383         return 1;
384 }
385
386 /* This method will attempt to get a message to a remote user.
387  */
388 void ModuleSpanningTree::RemoteMessage(User* user, const char* format, ...)
389 {
390         char text[MAXBUF];
391         va_list argsPtr;
392
393         va_start(argsPtr, format);
394         vsnprintf(text, MAXBUF, format, argsPtr);
395         va_end(argsPtr);
396
397         if (IS_LOCAL(user))
398                 user->WriteServ("NOTICE %s :%s", user->nick.c_str(), text);
399         else
400                 ServerInstance->PI->SendUserNotice(user, text);
401 }
402
403 int ModuleSpanningTree::HandleConnect(const std::vector<std::string>& parameters, User* user)
404 {
405         for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
406         {
407                 if (InspIRCd::Match(x->Name.c_str(),parameters[0]))
408                 {
409                         if (InspIRCd::Match(ServerInstance->Config->ServerName, assign(x->Name)))
410                         {
411                                 RemoteMessage(user, "*** CONNECT: Server \002%s\002 is ME, not connecting.",x->Name.c_str());
412                                 return 1;
413                         }
414
415                         TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
416                         if (!CheckDupe)
417                         {
418                                 RemoteMessage(user, "*** CONNECT: Connecting to server: \002%s\002 (%s:%d)",x->Name.c_str(),(x->HiddenFromStats ? "<hidden>" : x->IPAddr.c_str()),x->Port);
419                                 ConnectServer(&(*x));
420                                 return 1;
421                         }
422                         else
423                         {
424                                 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());
425                                 return 1;
426                         }
427                 }
428         }
429         RemoteMessage(user, "*** CONNECT: No server matching \002%s\002 could be found in the config file.",parameters[0].c_str());
430         return 1;
431 }
432
433 void ModuleSpanningTree::OnGetServerDescription(const std::string &servername,std::string &description)
434 {
435         TreeServer* s = Utils->FindServer(servername);
436         if (s)
437         {
438                 description = s->GetDesc();
439         }
440 }
441
442 void ModuleSpanningTree::OnUserInvite(User* source,User* dest,Channel* channel, time_t expiry)
443 {
444         if (IS_LOCAL(source))
445         {
446                 std::deque<std::string> params;
447                 params.push_back(dest->uuid);
448                 params.push_back(channel->name);
449                 params.push_back(ConvToStr(expiry));
450                 Utils->DoOneToMany(source->uuid,"INVITE",params);
451         }
452 }
453
454 void ModuleSpanningTree::OnPostLocalTopicChange(User* user, Channel* chan, const std::string &topic)
455 {
456         std::deque<std::string> params;
457         params.push_back(chan->name);
458         params.push_back(":"+topic);
459         Utils->DoOneToMany(user->uuid,"TOPIC",params);
460 }
461
462 void ModuleSpanningTree::OnWallops(User* user, const std::string &text)
463 {
464         if (IS_LOCAL(user))
465         {
466                 std::deque<std::string> params;
467                 params.push_back(":"+text);
468                 Utils->DoOneToMany(user->uuid,"WALLOPS",params);
469         }
470 }
471
472 void ModuleSpanningTree::OnUserNotice(User* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list)
473 {
474         /* Server origin */
475         if (user == NULL)
476                 return;
477
478         if (target_type == TYPE_USER)
479         {
480                 User* d = (User*)dest;
481                 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
482                 {
483                         std::deque<std::string> params;
484                         params.clear();
485                         params.push_back(d->uuid);
486                         params.push_back(":"+text);
487                         Utils->DoOneToOne(user->uuid,"NOTICE",params,d->server);
488                 }
489         }
490         else if (target_type == TYPE_CHANNEL)
491         {
492                 if (IS_LOCAL(user))
493                 {
494                         Channel *c = (Channel*)dest;
495                         if (c)
496                         {
497                                 std::string cname = c->name;
498                                 if (status)
499                                         cname = status + cname;
500                                 TreeServerList list;
501                                 Utils->GetListOfServersForChannel(c,list,status,exempt_list);
502                                 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
503                                 {
504                                         TreeSocket* Sock = i->second->GetSocket();
505                                         if (Sock)
506                                                 Sock->WriteLine(":"+std::string(user->uuid)+" NOTICE "+cname+" :"+text);
507                                 }
508                         }
509                 }
510         }
511         else if (target_type == TYPE_SERVER)
512         {
513                 if (IS_LOCAL(user))
514                 {
515                         char* target = (char*)dest;
516                         std::deque<std::string> par;
517                         par.push_back(target);
518                         par.push_back(":"+text);
519                         Utils->DoOneToMany(user->uuid,"NOTICE",par);
520                 }
521         }
522 }
523
524 void ModuleSpanningTree::OnUserMessage(User* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list)
525 {
526         /* Server origin */
527         if (user == NULL)
528                 return;
529
530         if (target_type == TYPE_USER)
531         {
532                 // route private messages which are targetted at clients only to the server
533                 // which needs to receive them
534                 User* d = (User*)dest;
535                 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
536                 {
537                         std::deque<std::string> params;
538                         params.clear();
539                         params.push_back(d->uuid);
540                         params.push_back(":"+text);
541                         Utils->DoOneToOne(user->uuid,"PRIVMSG",params,d->server);
542                 }
543         }
544         else if (target_type == TYPE_CHANNEL)
545         {
546                 if (IS_LOCAL(user))
547                 {
548                         Channel *c = (Channel*)dest;
549                         if (c)
550                         {
551                                 std::string cname = c->name;
552                                 if (status)
553                                         cname = status + cname;
554                                 TreeServerList list;
555                                 Utils->GetListOfServersForChannel(c,list,status,exempt_list);
556                                 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
557                                 {
558                                         TreeSocket* Sock = i->second->GetSocket();
559                                         if (Sock)
560                                                 Sock->WriteLine(":"+std::string(user->uuid)+" PRIVMSG "+cname+" :"+text);
561                                 }
562                         }
563                 }
564         }
565         else if (target_type == TYPE_SERVER)
566         {
567                 if (IS_LOCAL(user))
568                 {
569                         char* target = (char*)dest;
570                         std::deque<std::string> par;
571                         par.push_back(target);
572                         par.push_back(":"+text);
573                         Utils->DoOneToMany(user->uuid,"PRIVMSG",par);
574                 }
575         }
576 }
577
578 void ModuleSpanningTree::OnBackgroundTimer(time_t curtime)
579 {
580         AutoConnectServers(curtime);
581         DoPingChecks(curtime);
582         DoConnectTimeout(curtime);
583 }
584
585 void ModuleSpanningTree::OnUserJoin(User* user, Channel* channel, bool sync, bool &silent)
586 {
587         // Only do this for local users
588         if (IS_LOCAL(user))
589         {
590                 std::deque<std::string> params;
591                 // set up their permissions and the channel TS with FJOIN.
592                 // All users are FJOINed now, because a module may specify
593                 // new joining permissions for the user.
594                 params.push_back(channel->name);
595                 params.push_back(ConvToStr(channel->age));
596                 params.push_back(std::string("+") + channel->ChanModes(true));
597                 params.push_back(ServerInstance->Modes->ModeString(user, channel, false)+","+std::string(user->uuid));
598                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"FJOIN",params);
599         }
600 }
601
602 int ModuleSpanningTree::OnChangeLocalUserHost(User* user, const std::string &newhost)
603 {
604         if (user->registered != REG_ALL)
605                 return 0;
606
607         std::deque<std::string> params;
608         params.push_back(newhost);
609         Utils->DoOneToMany(user->uuid,"FHOST",params);
610         return 0;
611 }
612
613 void ModuleSpanningTree::OnChangeName(User* user, const std::string &gecos)
614 {
615         // only occurs for local clients
616         if (user->registered != REG_ALL)
617                 return;
618
619         std::deque<std::string> params;
620         params.push_back(gecos);
621         Utils->DoOneToMany(user->uuid,"FNAME",params);
622 }
623
624 void ModuleSpanningTree::OnUserPart(User* user, Channel* channel,  std::string &partmessage, bool &silent)
625 {
626         if (IS_LOCAL(user))
627         {
628                 std::deque<std::string> params;
629                 params.push_back(channel->name);
630                 if (!partmessage.empty())
631                         params.push_back(":"+partmessage);
632                 Utils->DoOneToMany(user->uuid,"PART",params);
633         }
634 }
635
636 void ModuleSpanningTree::OnUserQuit(User* user, const std::string &reason, const std::string &oper_message)
637 {
638         if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
639         {
640                 std::deque<std::string> params;
641
642                 if (oper_message != reason)
643                 {
644                         params.push_back(":"+oper_message);
645                         Utils->DoOneToMany(user->uuid,"OPERQUIT",params);
646                 }
647                 params.clear();
648                 params.push_back(":"+reason);
649                 Utils->DoOneToMany(user->uuid,"QUIT",params);
650         }
651
652         // Regardless, We need to modify the user Counts..
653         TreeServer* SourceServer = Utils->FindServer(user->server);
654         if (SourceServer)
655         {
656                 SourceServer->SetUserCount(-1); // decrement by 1
657         }
658 }
659
660 void ModuleSpanningTree::OnUserPostNick(User* user, const std::string &oldnick)
661 {
662         if (IS_LOCAL(user))
663         {
664                 std::deque<std::string> params;
665                 params.push_back(user->nick);
666
667                 /** IMPORTANT: We don't update the TS if the oldnick is just a case change of the newnick!
668                  */
669                 if (irc::string(user->nick.c_str()) != assign(oldnick))
670                         user->age = ServerInstance->Time();
671
672                 params.push_back(ConvToStr(user->age));
673                 Utils->DoOneToMany(user->uuid,"NICK",params);
674         }
675 }
676
677 void ModuleSpanningTree::OnUserKick(User* source, User* user, Channel* chan, const std::string &reason, bool &silent)
678 {
679         if ((source) && (IS_LOCAL(source)))
680         {
681                 std::deque<std::string> params;
682                 params.push_back(chan->name);
683                 params.push_back(user->uuid);
684                 params.push_back(":"+reason);
685                 Utils->DoOneToMany(source->uuid,"KICK",params);
686         }
687         else if (!source)
688         {
689                 std::deque<std::string> params;
690                 params.push_back(chan->name);
691                 params.push_back(user->uuid);
692                 params.push_back(":"+reason);
693                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"KICK",params);
694         }
695 }
696
697 void ModuleSpanningTree::OnRemoteKill(User* source, User* dest, const std::string &reason, const std::string &operreason)
698 {
699         if (!IS_LOCAL(source))
700                 return; // Only start routing if we're origin.
701
702         std::deque<std::string> params;
703         params.push_back(":"+reason);
704         Utils->DoOneToMany(dest->uuid,"OPERQUIT",params);
705         params.clear();
706         params.push_back(dest->uuid);
707         params.push_back(":"+reason);
708         dest->SetOperQuit(operreason);
709         Utils->DoOneToMany(source->uuid,"KILL",params);
710 }
711
712 void ModuleSpanningTree::OnRehash(User* user, const std::string &parameter)
713 {
714         ServerInstance->Logs->Log("remoterehash", DEBUG, "called with param %s", parameter.c_str());
715
716         // Send out to other servers
717         if (!parameter.empty() && parameter[0] != '-')
718         {
719                 ServerInstance->Logs->Log("remoterehash", DEBUG, "sending out lol");
720                 std::deque<std::string> params;
721                 params.push_back(parameter);
722                 Utils->DoOneToAllButSender(user ? user->uuid : ServerInstance->Config->GetSID(), "REHASH", params, user ? user->server : ServerInstance->Config->ServerName);
723         }
724
725         // Re-read config stuff
726         Utils->ReadConfiguration(true);
727 }
728
729 void ModuleSpanningTree::OnLoadModule(Module* mod, const std::string &name)
730 {
731         this->RedoConfig(mod, name);
732 }
733
734 void ModuleSpanningTree::OnUnloadModule(Module* mod, const std::string &name)
735 {
736         this->RedoConfig(mod, name);
737 }
738
739 void ModuleSpanningTree::RedoConfig(Module* mod, const std::string &name)
740 {
741         /* If m_sha256.so is loaded (we use this for HMAC) or any module implementing a BufferedSocket interface is loaded,
742          * then we need to re-read our config again taking this into account.
743          */
744         modulelist* ml = ServerInstance->Modules->FindInterface("BufferedSocketHook");
745         bool IsBufferSocketModule = false;
746
747         /* Did we find any modules? */
748         if (ml && std::find(ml->begin(), ml->end(), mod) != ml->end())
749                 IsBufferSocketModule = true;
750
751         if (name == "m_sha256.so" || IsBufferSocketModule)
752         {
753                 Utils->ReadConfiguration(true);
754         }
755 }
756
757 // note: the protocol does not allow direct umode +o except
758 // via NICK with 8 params. sending OPERTYPE infers +o modechange
759 // locally.
760 void ModuleSpanningTree::OnOper(User* user, const std::string &opertype)
761 {
762         if (IS_LOCAL(user))
763         {
764                 std::deque<std::string> params;
765                 params.push_back(opertype);
766                 Utils->DoOneToMany(user->uuid,"OPERTYPE",params);
767         }
768 }
769
770 void ModuleSpanningTree::OnAddLine(User* user, XLine *x)
771 {
772         if (!x->IsBurstable())
773                 return;
774
775         char data[MAXBUF];
776         snprintf(data,MAXBUF,"%s %s %s %lu %lu :%s", x->type.c_str(), x->Displayable(),
777         ServerInstance->Config->ServerName, (unsigned long)x->set_time, (unsigned long)x->duration, x->reason);
778         std::deque<std::string> params;
779         params.push_back(data);
780
781         if (!user)
782         {
783                 /* Server-set lines */
784                 Utils->DoOneToMany(ServerInstance->Config->GetSID(), "ADDLINE", params);
785         }
786         else if (IS_LOCAL(user))
787         {
788                 /* User-set lines */
789                 Utils->DoOneToMany(user->uuid, "ADDLINE", params);
790         }
791 }
792
793 void ModuleSpanningTree::OnDelLine(User* user, XLine *x)
794 {
795         if (x->type == "K")
796                 return;
797
798         char data[MAXBUF];
799         snprintf(data,MAXBUF,"%s %s", x->type.c_str(), x->Displayable());
800         std::deque<std::string> params;
801         params.push_back(data);
802
803         if (!user)
804         {
805                 /* Server-unset lines */
806                 Utils->DoOneToMany(ServerInstance->Config->GetSID(), "DELLINE", params);
807         }
808         else if (IS_LOCAL(user))
809         {
810                 /* User-unset lines */
811                 Utils->DoOneToMany(user->uuid, "DELLINE", params);
812         }
813 }
814
815 void ModuleSpanningTree::OnMode(User* user, void* dest, int target_type, const std::deque<std::string> &text, const std::deque<TranslateType> &translate)
816 {
817         if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
818         {
819                 std::deque<std::string> params;
820                 std::string command;
821                 std::string output_text;
822
823                 ServerInstance->Parser->TranslateUIDs(translate, text, output_text);
824
825                 if (target_type == TYPE_USER)
826                 {
827                         User* u = (User*)dest;
828                         params.push_back(u->uuid);
829                         params.push_back(output_text);
830                         command = "MODE";
831                 }
832                 else
833                 {
834                         Channel* c = (Channel*)dest;
835                         params.push_back(c->name);
836                         params.push_back(ConvToStr(c->age));
837                         params.push_back(output_text);
838                         command = "FMODE";
839                 }
840
841                 Utils->DoOneToMany(user->uuid, command, params);
842         }
843 }
844
845 int ModuleSpanningTree::OnSetAway(User* user, const std::string &awaymsg)
846 {
847         if (IS_LOCAL(user))
848         {
849                 if (awaymsg.empty())
850                 {
851                         std::deque<std::string> params;
852                         params.clear();
853                         Utils->DoOneToMany(user->uuid,"AWAY",params);
854                 }
855                 else
856                 {
857                         std::deque<std::string> params;
858                         params.push_back(":" + awaymsg);
859                         Utils->DoOneToMany(user->uuid,"AWAY",params);
860                 }
861         }
862
863         return 0;
864 }
865
866 void ModuleSpanningTree::ProtoSendMode(void* opaque, TargetTypeFlags target_type, void* target, const std::deque<std::string> &modeline, const std::deque<TranslateType> &translate)
867 {
868         TreeSocket* s = (TreeSocket*)opaque;
869         std::string output_text;
870
871         ServerInstance->Parser->TranslateUIDs(translate, modeline, output_text);
872
873         if (target)
874         {
875                 if (target_type == TYPE_USER)
876                 {
877                         User* u = (User*)target;
878                         s->WriteLine(std::string(":")+ServerInstance->Config->GetSID()+" MODE "+u->uuid+" "+output_text);
879                 }
880                 else if (target_type == TYPE_CHANNEL)
881                 {
882                         Channel* c = (Channel*)target;
883                         s->WriteLine(std::string(":")+ServerInstance->Config->GetSID()+" FMODE "+c->name+" "+ConvToStr(c->age)+" "+output_text);
884                 }
885         }
886 }
887
888 void ModuleSpanningTree::ProtoSendMetaData(void* opaque, TargetTypeFlags target_type, void* target, const std::string &extname, const std::string &extdata)
889 {
890         TreeSocket* s = (TreeSocket*)opaque;
891         if (target)
892         {
893                 if (target_type == TYPE_USER)
894                 {
895                         User* u = (User*)target;
896                         s->WriteLine(std::string(":")+ServerInstance->Config->GetSID()+" METADATA "+u->uuid+" "+extname+" :"+extdata);
897                 }
898                 else if (target_type == TYPE_CHANNEL)
899                 {
900                         Channel* c = (Channel*)target;
901                         s->WriteLine(std::string(":")+ServerInstance->Config->GetSID()+" METADATA "+c->name+" "+extname+" :"+extdata);
902                 }
903         }
904         if (target_type == TYPE_OTHER)
905         {
906                 s->WriteLine(std::string(":")+ServerInstance->Config->GetSID()+" METADATA * "+extname+" :"+extdata);
907         }
908 }
909
910 void ModuleSpanningTree::OnEvent(Event* event)
911 {
912         if ((event->GetEventID() == "send_encap") || (event->GetEventID() == "send_metadata") || (event->GetEventID() == "send_topic") || (event->GetEventID() == "send_mode") || (event->GetEventID() == "send_mode_explicit") || (event->GetEventID() == "send_opers")
913                 || (event->GetEventID() == "send_modeset") || (event->GetEventID() == "send_snoset") || (event->GetEventID() == "send_push"))
914         {
915                 ServerInstance->Logs->Log("m_spanningtree", DEBUG, "WARNING: Deprecated use of old 1.1 style m_spanningtree event ignored, type '"+event->GetEventID()+"'!");
916         }
917 }
918
919 ModuleSpanningTree::~ModuleSpanningTree()
920 {
921         delete ServerInstance->PI;
922         ServerInstance->PI = new ProtocolInterface(ServerInstance);
923
924         /* This will also free the listeners */
925         delete Utils;
926
927         ServerInstance->Timers->DelTimer(RefreshTimer);
928
929         ServerInstance->Modules->DoneWithInterface("BufferedSocketHook");
930 }
931
932 Version ModuleSpanningTree::GetVersion()
933 {
934         return Version("$Id$", VF_VENDOR, API_VERSION);
935 }
936
937 /* It is IMPORTANT that m_spanningtree is the last module in the chain
938  * so that any activity it sees is FINAL, e.g. we arent going to send out
939  * a NICK message before m_cloaking has finished putting the +x on the user,
940  * etc etc.
941  * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
942  * the module call queue.
943  */
944 void ModuleSpanningTree::Prioritize()
945 {
946         ServerInstance->Modules->SetPriority(this, PRIORITY_LAST);
947 }
948
949 MODULE_INIT(ModuleSpanningTree)