]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/main.cpp
Add basic stuff for protocol interface and implement a couple of the methods. It...
[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 #include "m_spanningtree/protocolinterface.h"
34
35 /* $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 m_spanningtree/protocolinterface.h */
36
37 ModuleSpanningTree::ModuleSpanningTree(InspIRCd* Me)
38         : Module(Me), max_local(0), max_global(0)
39 {
40         ServerInstance->Modules->UseInterface("BufferedSocketHook");
41         Utils = new SpanningTreeUtilities(ServerInstance, this);
42         command_rconnect = new cmd_rconnect(ServerInstance, this, Utils);
43         ServerInstance->AddCommand(command_rconnect);
44         command_rsquit = new cmd_rsquit(ServerInstance, this, Utils);
45         ServerInstance->AddCommand(command_rsquit);
46         RefreshTimer = new CacheRefreshTimer(ServerInstance, Utils);
47         ServerInstance->Timers->AddTimer(RefreshTimer);
48
49         Implementation eventlist[] =
50         {
51                 I_OnPreCommand, I_OnGetServerDescription, I_OnUserInvite, I_OnPostLocalTopicChange,
52                 I_OnWallops, I_OnUserNotice, I_OnUserMessage, I_OnBackgroundTimer,
53                 I_OnUserJoin, I_OnChangeHost, I_OnChangeName, I_OnUserPart, I_OnPostConnect,
54                 I_OnUserQuit, I_OnUserPostNick, I_OnUserKick, I_OnRemoteKill, I_OnRehash,
55                 I_OnOper, I_OnAddLine, I_OnDelLine, I_ProtoSendMode, I_OnMode,
56                 I_OnStats, I_ProtoSendMetaData, I_OnEvent, I_OnSetAway, I_OnPostCommand
57         };
58         ServerInstance->Modules->Attach(eventlist, this, 28);
59
60         delete ServerInstance->PI;
61         ServerInstance->PI = new SpanningTreeProtocolInterface(this, Utils, ServerInstance);
62
63         for (std::vector<User*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
64         {
65                 this->OnPostConnect((*i));
66         }
67 }
68
69 void ModuleSpanningTree::ShowLinks(TreeServer* Current, User* user, int hops)
70 {
71         std::string Parent = Utils->TreeRoot->GetName();
72         if (Current->GetParent())
73         {
74                 Parent = Current->GetParent()->GetName();
75         }
76         for (unsigned int q = 0; q < Current->ChildCount(); q++)
77         {
78                 if ((Current->GetChild(q)->Hidden) || ((Utils->HideULines) && (ServerInstance->ULine(Current->GetChild(q)->GetName().c_str()))))
79                 {
80                         if (*user->oper)
81                         {
82                                  ShowLinks(Current->GetChild(q),user,hops+1);
83                         }
84                 }
85                 else
86                 {
87                         ShowLinks(Current->GetChild(q),user,hops+1);
88                 }
89         }
90         /* Don't display the line if its a uline, hide ulines is on, and the user isnt an oper */
91         if ((Utils->HideULines) && (ServerInstance->ULine(Current->GetName().c_str())) && (!IS_OPER(user)))
92                 return;
93         /* Or if the server is hidden and they're not an oper */
94         else if ((Current->Hidden) && (!IS_OPER(user)))
95                 return;
96
97         user->WriteNumeric(364, "%s %s %s :%d %s",      user->nick,Current->GetName().c_str(),
98                         (Utils->FlatLinks && (!IS_OPER(user))) ? ServerInstance->Config->ServerName : Parent.c_str(),
99                         (Utils->FlatLinks && (!IS_OPER(user))) ? 0 : hops,
100                         Current->GetDesc().c_str());
101 }
102
103 int ModuleSpanningTree::CountLocalServs()
104 {
105         return Utils->TreeRoot->ChildCount();
106 }
107
108 int ModuleSpanningTree::CountServs()
109 {
110         return Utils->serverlist.size();
111 }
112
113 void ModuleSpanningTree::HandleLinks(const char* const* parameters, int pcnt, User* user)
114 {
115         ShowLinks(Utils->TreeRoot,user,0);
116         user->WriteNumeric(365, "%s * :End of /LINKS list.",user->nick);
117         return;
118 }
119
120 void ModuleSpanningTree::HandleLusers(const char* const* parameters, int pcnt, User* user)
121 {
122         unsigned int n_users = ServerInstance->Users->UserCount();
123
124         /* Only update these when someone wants to see them, more efficient */
125         if ((unsigned int)ServerInstance->Users->LocalUserCount() > max_local)
126                 max_local = ServerInstance->Users->LocalUserCount();
127         if (n_users > max_global)
128                 max_global = n_users;
129
130         unsigned int ulined_count = 0;
131         unsigned int ulined_local_count = 0;
132
133         /* If ulined are hidden and we're not an oper, count the number of ulined servers hidden,
134          * locally and globally (locally means directly connected to us)
135          */
136         if ((Utils->HideULines) && (!*user->oper))
137         {
138                 for (server_hash::iterator q = Utils->serverlist.begin(); q != Utils->serverlist.end(); q++)
139                 {
140                         if (ServerInstance->ULine(q->second->GetName().c_str()))
141                         {
142                                 ulined_count++;
143                                 if (q->second->GetParent() == Utils->TreeRoot)
144                                         ulined_local_count++;
145                         }
146                 }
147         }
148         user->WriteNumeric(251, "%s :There are %d users and %d invisible on %d servers",user->nick,
149                         n_users-ServerInstance->Users->ModeCount('i'),
150                         ServerInstance->Users->ModeCount('i'),
151                         ulined_count ? this->CountServs() - ulined_count : this->CountServs());
152
153         if (ServerInstance->Users->OperCount())
154                 user->WriteNumeric(252, "%s %d :operator(s) online",user->nick,ServerInstance->Users->OperCount());
155
156         if (ServerInstance->Users->UnregisteredUserCount())
157                 user->WriteNumeric(253, "%s %d :unknown connections",user->nick,ServerInstance->Users->UnregisteredUserCount());
158         
159         if (ServerInstance->ChannelCount())
160                 user->WriteNumeric(254, "%s %ld :channels formed",user->nick,ServerInstance->ChannelCount());
161         
162         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());
163         user->WriteNumeric(265, "%s :Current Local Users: %d  Max: %d",user->nick,ServerInstance->Users->LocalUserCount(),max_local);
164         user->WriteNumeric(266, "%s :Current Global Users: %d  Max: %d",user->nick,n_users,max_global);
165         return;
166 }
167
168 std::string ModuleSpanningTree::TimeToStr(time_t secs)
169 {
170         time_t mins_up = secs / 60;
171         time_t hours_up = mins_up / 60;
172         time_t days_up = hours_up / 24;
173         secs = secs % 60;
174         mins_up = mins_up % 60;
175         hours_up = hours_up % 24;
176         return ((days_up ? (ConvToStr(days_up) + "d") : std::string(""))
177                         + (hours_up ? (ConvToStr(hours_up) + "h") : std::string(""))
178                         + (mins_up ? (ConvToStr(mins_up) + "m") : std::string(""))
179                         + ConvToStr(secs) + "s");
180 }
181
182 void ModuleSpanningTree::DoPingChecks(time_t curtime)
183 {
184         for (unsigned int j = 0; j < Utils->TreeRoot->ChildCount(); j++)
185         {
186                 TreeServer* serv = Utils->TreeRoot->GetChild(j);
187                 TreeSocket* sock = serv->GetSocket();
188                 if (sock)
189                 {
190                         if (curtime >= serv->NextPingTime())
191                         {
192                                 if (serv->AnsweredLastPing())
193                                 {
194                                         sock->WriteLine(std::string(":")+ServerInstance->Config->GetSID()+" PING "+serv->GetID());
195                                         serv->SetNextPingTime(curtime + Utils->PingFreq);
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         /*
222          * Cancel remote burst mode on any servers which still have it enabled due to latency/lack of data.
223          * This prevents lost REMOTECONNECT notices
224          * XXX this should probably not do this until server has been bursting for, say, 60 seconds or something
225          */
226         for (server_hash::iterator i = Utils->serverlist.begin(); i != Utils->serverlist.end(); i++)
227         {
228                 if (i->second->bursting)
229                 {
230                         ServerInstance->SNO->WriteToSnoMask('l',"Server \002%s\002 has not finished burst, forcing end of burst.", i->second->GetName().c_str());
231                         i->second->FinishBurst();
232                 }
233         }
234 }
235
236 void ModuleSpanningTree::ConnectServer(Link* x)
237 {
238         bool ipvalid = true;
239         QueryType start_type = DNS_QUERY_A;
240 #ifdef IPV6
241         start_type = DNS_QUERY_AAAA;
242         if (strchr(x->IPAddr.c_str(),':'))
243         {
244                 in6_addr n;
245                 if (inet_pton(AF_INET6, x->IPAddr.c_str(), &n) < 1)
246                         ipvalid = false;
247         }
248         else
249 #endif
250         {
251                 in_addr n;
252                 if (inet_aton(x->IPAddr.c_str(),&n) < 1)
253                         ipvalid = false;
254         }
255
256         /* Do we already have an IP? If so, no need to resolve it. */
257         if (ipvalid)
258         {
259                 /* Gave a hook, but it wasnt one we know */
260                 if ((!x->Hook.empty()) && (Utils->hooks.find(x->Hook.c_str()) == Utils->hooks.end()))
261                         return;
262                 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()]);
263                 if (newsocket->GetFd() > -1)
264                 {
265                         /* Handled automatically on success */
266                 }
267                 else
268                 {
269                         RemoteMessage(NULL, "CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(),strerror(errno));
270                         if (ServerInstance->SocketCull.find(newsocket) == ServerInstance->SocketCull.end())
271                                 ServerInstance->SocketCull[newsocket] = newsocket;
272                         Utils->DoFailOver(x);
273                 }
274         }
275         else
276         {
277                 try
278                 {
279                         bool cached;
280                         ServernameResolver* snr = new ServernameResolver((Module*)this, Utils, ServerInstance,x->IPAddr, *x, cached, start_type);
281                         ServerInstance->AddResolver(snr, cached);
282                 }
283                 catch (ModuleException& e)
284                 {
285                         RemoteMessage(NULL, "CONNECT: Error connecting \002%s\002: %s.",x->Name.c_str(), e.GetReason());
286                         Utils->DoFailOver(x);
287                 }
288         }
289 }
290
291 void ModuleSpanningTree::AutoConnectServers(time_t curtime)
292 {
293         for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
294         {
295                 if ((x->AutoConnect) && (curtime >= x->NextConnectTime))
296                 {
297                         x->NextConnectTime = curtime + x->AutoConnect;
298                         TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
299                         if (x->FailOver.length())
300                         {
301                                 TreeServer* CheckFailOver = Utils->FindServer(x->FailOver.c_str());
302                                 if (CheckFailOver)
303                                 {
304                                         /* The failover for this server is currently a member of the network.
305                                          * The failover probably succeeded, where the main link did not.
306                                          * Don't try the main link until the failover is gone again.
307                                          */
308                                         continue;
309                                 }
310                         }
311                         if (!CheckDupe)
312                         {
313                                 // an autoconnected server is not connected. Check if its time to connect it
314                                 ServerInstance->SNO->WriteToSnoMask('l',"AUTOCONNECT: Auto-connecting server \002%s\002 (%lu seconds until next attempt)",x->Name.c_str(),x->AutoConnect);
315                                 this->ConnectServer(&(*x));
316                         }
317                 }
318         }
319 }
320
321 int ModuleSpanningTree::HandleVersion(const char* const* parameters, int pcnt, User* user)
322 {
323         // we've already checked if pcnt > 0, so this is safe
324         TreeServer* found = Utils->FindServerMask(parameters[0]);
325         if (found)
326         {
327                 std::string Version = found->GetVersion();
328                 user->WriteNumeric(351, "%s :%s",user->nick,Version.c_str());
329                 if (found == Utils->TreeRoot)
330                 {
331                         ServerInstance->Config->Send005(user);
332                 }
333         }
334         else
335         {
336                 user->WriteNumeric(402, "%s %s :No such server",user->nick,parameters[0]);
337         }
338         return 1;
339 }
340
341 /* This method will attempt to get a link message out to as many people as is required.
342  * If a user is provided, and that user is local, then the user is sent the message using
343  * WriteServ (they are the local initiator of that message). If the user is remote, they are
344  * sent that message remotely via PUSH.
345  * If the user is NULL, then the notice is sent locally via WriteToSnoMask with snomask 'l',
346  * and remotely via SNONOTICE with mask 'l'.
347  */
348 void ModuleSpanningTree::RemoteMessage(User* user, const char* format, ...)
349 {
350         /* This could cause an infinite loop, because DoOneToMany() will, on error,
351          * call TreeSocket::OnError(), which in turn will call this function to
352          * notify everyone of the error. So, drop any messages that are generated
353          * during the sending of another message. -Special */
354         static bool SendingRemoteMessage = false;
355         if (SendingRemoteMessage)
356                 return;
357         SendingRemoteMessage = true;
358
359         std::deque<std::string> params;
360         char text[MAXBUF];
361         va_list argsPtr;
362
363         va_start(argsPtr, format);
364         vsnprintf(text, MAXBUF, format, argsPtr);
365         va_end(argsPtr);
366
367         if (!user)
368         {
369                 /* No user, target it generically at everyone */
370                 ServerInstance->SNO->WriteToSnoMask('l', "%s", text);
371                 params.push_back("l");
372                 params.push_back(std::string(":") + text);
373                 Utils->DoOneToMany(ServerInstance->Config->GetSID(), "SNONOTICE", params);
374         }
375         else
376         {
377                 if (IS_LOCAL(user))
378                         user->WriteServ("NOTICE %s :%s", user->nick, text);
379                 else
380                 {
381                         params.push_back(user->uuid);
382                         params.push_back(std::string("::") + ServerInstance->Config->ServerName + " NOTICE " + user->nick + " :*** From " +
383                                         ServerInstance->Config->ServerName+ ": " + text);
384                         Utils->DoOneToMany(ServerInstance->Config->GetSID(), "PUSH", params);
385                 }
386         }
387         
388         SendingRemoteMessage = false;
389 }
390         
391 int ModuleSpanningTree::HandleConnect(const char* const* parameters, int pcnt, User* user)
392 {
393         for (std::vector<Link>::iterator x = Utils->LinkBlocks.begin(); x < Utils->LinkBlocks.end(); x++)
394         {
395                 if (ServerInstance->MatchText(x->Name.c_str(),parameters[0]))
396                 {
397                         TreeServer* CheckDupe = Utils->FindServer(x->Name.c_str());
398                         if (!CheckDupe)
399                         {
400                                 RemoteMessage(user, "*** CONNECT: Connecting to server: \002%s\002 (%s:%d)",x->Name.c_str(),(x->HiddenFromStats ? "<hidden>" : x->IPAddr.c_str()),x->Port);
401                                 ConnectServer(&(*x));
402                                 return 1;
403                         }
404                         else
405                         {
406                                 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());
407                                 return 1;
408                         }
409                 }
410         }
411         RemoteMessage(user, "*** CONNECT: No server matching \002%s\002 could be found in the config file.",parameters[0]);
412         return 1;
413 }
414
415 void ModuleSpanningTree::OnGetServerDescription(const std::string &servername,std::string &description)
416 {
417         TreeServer* s = Utils->FindServer(servername);
418         if (s)
419         {
420                 description = s->GetDesc();
421         }
422 }
423
424 void ModuleSpanningTree::OnUserInvite(User* source,User* dest,Channel* channel, time_t expiry)
425 {
426         if (IS_LOCAL(source))
427         {
428                 std::deque<std::string> params;
429                 params.push_back(dest->uuid);
430                 params.push_back(channel->name);
431                 params.push_back(ConvToStr(expiry));
432                 Utils->DoOneToMany(source->uuid,"INVITE",params);
433         }
434 }
435
436 void ModuleSpanningTree::OnPostLocalTopicChange(User* user, Channel* chan, const std::string &topic)
437 {
438         std::deque<std::string> params;
439         params.push_back(chan->name);
440         params.push_back(":"+topic);
441         Utils->DoOneToMany(user->uuid,"TOPIC",params);
442 }
443
444 void ModuleSpanningTree::OnWallops(User* user, const std::string &text)
445 {
446         if (IS_LOCAL(user))
447         {
448                 std::deque<std::string> params;
449                 params.push_back(":"+text);
450                 Utils->DoOneToMany(user->uuid,"WALLOPS",params);
451         }
452 }
453
454 void ModuleSpanningTree::OnUserNotice(User* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list)
455 {
456         if (target_type == TYPE_USER)
457         {
458                 User* d = (User*)dest;
459                 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
460                 {
461                         std::deque<std::string> params;
462                         params.clear();
463                         params.push_back(d->uuid);
464                         params.push_back(":"+text);
465                         Utils->DoOneToOne(user->uuid,"NOTICE",params,d->server);
466                 }
467         }
468         else if (target_type == TYPE_CHANNEL)
469         {
470                 if (IS_LOCAL(user))
471                 {
472                         Channel *c = (Channel*)dest;
473                         if (c)
474                         {
475                                 std::string cname = c->name;
476                                 if (status)
477                                         cname = status + cname;
478                                 TreeServerList list;
479                                 Utils->GetListOfServersForChannel(c,list,status,exempt_list);
480                                 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
481                                 {
482                                         TreeSocket* Sock = i->second->GetSocket();
483                                         if (Sock)
484                                                 Sock->WriteLine(":"+std::string(user->uuid)+" NOTICE "+cname+" :"+text);
485                                 }
486                         }
487                 }
488         }
489         else if (target_type == TYPE_SERVER)
490         {
491                 if (IS_LOCAL(user))
492                 {
493                         char* target = (char*)dest;
494                         std::deque<std::string> par;
495                         par.push_back(target);
496                         par.push_back(":"+text);
497                         Utils->DoOneToMany(user->uuid,"NOTICE",par);
498                 }
499         }
500 }
501
502 void ModuleSpanningTree::OnUserMessage(User* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list)
503 {
504         if (target_type == TYPE_USER)
505         {
506                 // route private messages which are targetted at clients only to the server
507                 // which needs to receive them
508                 User* d = (User*)dest;
509                 if ((d->GetFd() < 0) && (IS_LOCAL(user)))
510                 {
511                         std::deque<std::string> params;
512                         params.clear();
513                         params.push_back(d->uuid);
514                         params.push_back(":"+text);
515                         Utils->DoOneToOne(user->uuid,"PRIVMSG",params,d->server);
516                 }
517         }
518         else if (target_type == TYPE_CHANNEL)
519         {
520                 if (IS_LOCAL(user))
521                 {
522                         Channel *c = (Channel*)dest;
523                         if (c)
524                         {
525                                 std::string cname = c->name;
526                                 if (status)
527                                         cname = status + cname;
528                                 TreeServerList list;
529                                 Utils->GetListOfServersForChannel(c,list,status,exempt_list);
530                                 for (TreeServerList::iterator i = list.begin(); i != list.end(); i++)
531                                 {
532                                         TreeSocket* Sock = i->second->GetSocket();
533                                         if (Sock)
534                                                 Sock->WriteLine(":"+std::string(user->uuid)+" PRIVMSG "+cname+" :"+text);
535                                 }
536                         }
537                 }
538         }
539         else if (target_type == TYPE_SERVER)
540         {
541                 if (IS_LOCAL(user))
542                 {
543                         char* target = (char*)dest;
544                         std::deque<std::string> par;
545                         par.push_back(target);
546                         par.push_back(":"+text);
547                         Utils->DoOneToMany(user->uuid,"PRIVMSG",par);
548                 }
549         }
550 }
551
552 void ModuleSpanningTree::OnBackgroundTimer(time_t curtime)
553 {
554         AutoConnectServers(curtime);
555         DoPingChecks(curtime);
556 }
557
558 void ModuleSpanningTree::OnUserJoin(User* user, Channel* channel, bool sync, bool &silent)
559 {
560         // Only do this for local users
561         if (IS_LOCAL(user))
562         {
563                 if (channel->GetUserCounter() == 1)
564                 {
565                         std::deque<std::string> params;
566                         // set up their permissions and the channel TS with FJOIN.
567                         // All users are FJOINed now, because a module may specify
568                         // new joining permissions for the user.
569                         params.push_back(channel->name);
570                         params.push_back(ConvToStr(channel->age));
571                         params.push_back(std::string(channel->GetAllPrefixChars(user))+","+std::string(user->uuid));
572                         Utils->DoOneToMany(ServerInstance->Config->GetSID(),"FJOIN",params);
573                         /* First user in, sync the modes for the channel */
574                         params.pop_back();
575                         params.push_back(std::string("+") + channel->ChanModes(true));
576                         Utils->DoOneToMany(ServerInstance->Config->GetSID(),"FMODE",params);
577                 }
578                 else
579                 {
580                         std::deque<std::string> params;
581                         params.push_back(channel->name);
582                         params.push_back(ConvToStr(channel->age));
583                         Utils->DoOneToMany(user->uuid,"JOIN",params);
584                 }
585         }
586 }
587
588 void ModuleSpanningTree::OnChangeHost(User* user, const std::string &newhost)
589 {
590         // only occurs for local clients
591         if (user->registered != REG_ALL)
592                 return;
593         std::deque<std::string> params;
594         params.push_back(newhost);
595         Utils->DoOneToMany(user->uuid,"FHOST",params);
596 }
597
598 void ModuleSpanningTree::OnChangeName(User* user, const std::string &gecos)
599 {
600         // only occurs for local clients
601         if (user->registered != REG_ALL)
602                 return;
603         std::deque<std::string> params;
604         params.push_back(gecos);
605         Utils->DoOneToMany(user->uuid,"FNAME",params);
606 }
607
608 void ModuleSpanningTree::OnUserPart(User* user, Channel* channel, const std::string &partmessage, bool &silent)
609 {
610         if (IS_LOCAL(user))
611         {
612                 std::deque<std::string> params;
613                 params.push_back(channel->name);
614                 if (!partmessage.empty())
615                         params.push_back(":"+partmessage);
616                 Utils->DoOneToMany(user->uuid,"PART",params);
617         }
618 }
619
620 void ModuleSpanningTree::OnPostConnect(User* user)
621 {
622         if (IS_LOCAL(user))
623         {
624                 std::deque<std::string> params;
625                 params.push_back(user->uuid);
626                 params.push_back(ConvToStr(user->age));
627                 params.push_back(user->nick);
628                 params.push_back(user->host);
629                 params.push_back(user->dhost);
630                 params.push_back(user->ident);
631                 params.push_back("+"+std::string(user->FormatModes()));
632                 params.push_back(user->GetIPString());
633                 params.push_back(ConvToStr(user->signon));
634                 params.push_back(":"+std::string(user->fullname));
635                 Utils->DoOneToMany(ServerInstance->Config->GetSID(), "UID", params);
636         }
637
638         TreeServer* SourceServer = Utils->FindServer(user->server);
639         if (SourceServer)
640         {
641                 SourceServer->SetUserCount(1); // increment by 1
642         }
643 }
644
645 void ModuleSpanningTree::OnUserQuit(User* user, const std::string &reason, const std::string &oper_message)
646 {
647         if ((IS_LOCAL(user)) && (user->registered == REG_ALL))
648         {
649                 std::deque<std::string> params;
650
651                 if (oper_message != reason)
652                 {
653                         params.push_back(":"+oper_message);
654                         Utils->DoOneToMany(user->uuid,"OPERQUIT",params);
655                 }
656                 params.clear();
657                 params.push_back(":"+reason);
658                 Utils->DoOneToMany(user->uuid,"QUIT",params);
659         }
660
661         // Regardless, We need to modify the user Counts..
662         TreeServer* SourceServer = Utils->FindServer(user->server);
663         if (SourceServer)
664         {
665                 SourceServer->SetUserCount(-1); // decrement by 1
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();
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->SNO->WriteToSnoMask('A', "Remote rehash initiated locally by \002%s\002", user ? user->nick : ServerInstance->Config->ServerName);
729                         ServerInstance->RehashServer();
730                 }
731         }
732         Utils->ReadConfiguration(true);
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(User* user, XLine *x)
750 {
751         if (!x->IsBurstable())
752                 return;
753
754         char data[MAXBUF];
755         snprintf(data,MAXBUF,"%s %s %s %lu %lu :%s", x->type.c_str(), x->Displayable(), 
756         ServerInstance->Config->ServerName, (unsigned long)x->set_time, (unsigned long)x->duration, x->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(User* user, XLine *x)
773 {
774         if (x->type == "K")
775                 return;
776
777         char data[MAXBUF];
778         snprintf(data,MAXBUF,"%s %s", x->type.c_str(), x->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 int ModuleSpanningTree::OnSetAway(User* user, const std::string &awaymsg)
825 {
826         if (IS_LOCAL(user))
827         {
828                 if (awaymsg.empty())
829                 {
830                         std::deque<std::string> params;
831                         params.clear();
832                         Utils->DoOneToMany(user->uuid,"AWAY",params);
833                 }
834                 else
835                 {
836                         std::deque<std::string> params;
837                         params.push_back(":" + awaymsg);
838                         Utils->DoOneToMany(user->uuid,"AWAY",params);
839                 }
840         }
841
842         return 0;
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_encap")
893         {
894                 if (params->size() < 2)
895                         return;
896
897                 Utils->DoOneToMany(ServerInstance->Config->GetSID(), "ENCAP", *params);
898         }
899         else if (event->GetEventID() == "send_metadata")
900         {
901                 if (params->size() < 3)
902                         return;
903                 (*params)[2] = ":" + (*params)[2];
904                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"METADATA",*params);
905         }
906         else if (event->GetEventID() == "send_topic")
907         {
908                 if (params->size() < 2)
909                         return;
910                 (*params)[1] = ":" + (*params)[1];
911                 params->insert(params->begin() + 1,ServerInstance->Config->ServerName);
912                 params->insert(params->begin() + 1,ConvToStr(ServerInstance->Time()));
913                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"FTOPIC",*params);
914         }
915         else if (event->GetEventID() == "send_mode")
916         {
917                 if (params->size() < 2)
918                         return;
919                 // Insert the TS value of the object, either User or Channel
920                 time_t ourTS = 0;
921                 std::string output_text;
922
923                 /* Warning: in-place translation is only safe for type TR_NICK */
924                 for (size_t n = 0; n < params->size(); n++)
925                         ServerInstance->Parser->TranslateUIDs(TR_NICK, (*params)[n], (*params)[n]);
926
927                 User* a = ServerInstance->FindNick((*params)[0]);
928                 if (a)
929                 {
930                         ourTS = a->age;
931                         Utils->DoOneToMany(ServerInstance->Config->GetSID(),"MODE",*params);
932                         return;
933                 }
934                 else
935                 {
936                         Channel* c = ServerInstance->FindChan((*params)[0]);
937                         if (c)
938                         {
939                                 ourTS = c->age;
940                                 params->insert(params->begin() + 1,ConvToStr(ourTS));
941                                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"FMODE",*params);
942                         }
943                 }
944         }
945         else if (event->GetEventID() == "send_mode_explicit")
946         {
947                 if (params->size() < 2)
948                         return;
949                 std::string output_text;
950
951                 /* Warning: in-place translation is only safe for type TR_NICK */
952                 for (size_t n = 0; n < params->size(); n++)
953                         ServerInstance->Parser->TranslateUIDs(TR_NICK, (*params)[n], (*params)[n]);
954
955                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"MODE",*params);
956         }
957         else if (event->GetEventID() == "send_opers")
958         {
959                 if (params->size() < 1)
960                         return;
961                 (*params)[0] = ":" + (*params)[0];
962                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"OPERNOTICE",*params);
963         }
964         else if (event->GetEventID() == "send_modeset")
965         {
966                 if (params->size() < 2)
967                         return;
968                 (*params)[1] = ":" + (*params)[1];
969                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"MODENOTICE",*params);
970         }
971         else if (event->GetEventID() == "send_snoset")
972         {
973                 if (params->size() < 2)
974                         return;
975                 (*params)[1] = ":" + (*params)[1];
976                 Utils->DoOneToMany(ServerInstance->Config->GetSID(),"SNONOTICE",*params);
977         }
978         else if (event->GetEventID() == "send_push")
979         {
980                 if (params->size() < 2)
981                         return;
982                         
983                 User *a = ServerInstance->FindNick((*params)[0]);
984                         
985                 if (!a)
986                         return;
987
988                 (*params)[0] = a->uuid;
989                 (*params)[1] = ":" + (*params)[1];
990                 Utils->DoOneToOne(ServerInstance->Config->GetSID(), "PUSH", *params, a->server);
991         }
992 }
993
994 ModuleSpanningTree::~ModuleSpanningTree()
995 {
996         /* This will also free the listeners */
997         delete ServerInstance->PI;
998         ServerInstance->PI = new ProtocolInterface(ServerInstance);
999
1000         delete Utils;
1001
1002         ServerInstance->Timers->DelTimer(RefreshTimer);
1003
1004         ServerInstance->Modules->DoneWithInterface("BufferedSocketHook");
1005 }
1006
1007 Version ModuleSpanningTree::GetVersion()
1008 {
1009         return Version(1,2,0,2,VF_VENDOR,API_VERSION);
1010 }
1011
1012 /* It is IMPORTANT that m_spanningtree is the last module in the chain
1013  * so that any activity it sees is FINAL, e.g. we arent going to send out
1014  * a NICK message before m_cloaking has finished putting the +x on the user,
1015  * etc etc.
1016  * Therefore, we return PRIORITY_LAST to make sure we end up at the END of
1017  * the module call queue.
1018  */
1019 void ModuleSpanningTree::Prioritize()
1020 {
1021         ServerInstance->Modules->SetPriority(this, PRIO_LAST);
1022 }
1023
1024 MODULE_INIT(ModuleSpanningTree)