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