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