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