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