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